<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Meital Karamani on Medium]]></title>
        <description><![CDATA[Stories by Meital Karamani on Medium]]></description>
        <link>https://medium.com/@meitalka?source=rss-3e9bc76d535f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LcB7dnxWRKlv7jfR-yVNRA@2x.jpeg</url>
            <title>Stories by Meital Karamani on Medium</title>
            <link>https://medium.com/@meitalka?source=rss-3e9bc76d535f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 02:31:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@meitalka/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[GORM Soft Delete: How to Update the updated_at Field Automatically]]></title>
            <link>https://medium.com/tailor-tech/gorm-soft-delete-how-to-update-the-updated-at-field-automatically-7da7817f796a?source=rss-3e9bc76d535f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7da7817f796a</guid>
            <category><![CDATA[orm]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[data-integrity]]></category>
            <category><![CDATA[gorm]]></category>
            <dc:creator><![CDATA[Meital Karamani]]></dc:creator>
            <pubDate>Thu, 15 May 2025 13:29:30 GMT</pubDate>
            <atom:updated>2025-08-13T10:48:34.112Z</atom:updated>
            <content:encoded><![CDATA[<p>Modern applications rely on accurate timestamps to reflect data lifecycle events such as creations, updates, and deletions. In many systems, it’s crucial to know exactly when a record was deleted or even just <strong>marked</strong> as deleted (soft delete - more on when and why to use it, at a different time). By default, GORM, a popular ORM library for Go, doesn’t update the updated_at timestamp when a record is deleted, leaving a potential gap in your data audit trail.</p><p>In this article, I’ll walk you through:</p><ol><li>Why updated_at matters even on delete actions.</li><li>A custom GORM callback that updates updated_at during soft deletes.</li><li>Benefits &amp; Best Practices</li><li>Transactions &amp; Data Safety</li><li>Potential Considerations</li><li>Conclusion</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6mM_xz0eWS_Nge1N-uzbyg.png" /></figure><h4><strong>1. Why updated_at Matters on Delete</strong></h4><p><strong>GORM Timestamps<br></strong>GORM provides three main timestamps for any struct that embeds gorm.Modelor similarly defines them explicitly:</p><p>• <strong>CreatedAt</strong>: Automatically set when a record is created.</p><p>• <strong>UpdatedAt</strong>: Automatically updated when a record is created/modified.</p><p>• <strong>DeletedAt</strong> (optional): Used for soft deletes (if you want to mark something as deleted rather than physically removing it from the database).</p><p>However, when you perform a soft delete, GORM does <strong>not</strong> automatically update updated_at. This can create confusion or inconsistencies in data tracking, some examples include:</p><p>• <strong>Audit Trails</strong>: If your logs or data pipelines rely on updated_at to detect changes, they’ll miss soft-delete events.</p><p>• <strong>Analytics</strong>: Data engineers often pull data incrementally using the highest updated_at to only handle the relevant records. A lack of update on delete may prevent them from capturing these records.</p><p>• <strong>Compliance</strong>: Certain regulations or internal best practices require precise records of data modifications, including deletions.</p><p>Understanding this limitation is crucial, as it impacts data reliability and auditability. In the next section, we’ll address how to resolve this issue with a custom GORM callback.</p><h4><strong>2. A Custom GORM Callback to Update updated_at on Delete</strong></h4><p>To address this limitation, we can leverage GORM’s callbacks. A callback in GORM lets you override or extend the default CRUD (Create, Read, Update, Delete) operations with your own logic. Here’s how we can hook into the Delete lifecycle and leverage GORM’s callback mechanism to automatically handle updates to the updated_at field upon soft deletes:</p><p>🧩 Key Parts of the Code</p><pre>// DeleteCallback replaces GORM&#39;s default delete behavior<br>func DeleteCallback(db *gorm.DB) {<br> if db.Error != nil || db.Statement.Schema == nil {<br>  return<br> }<br><br> // Add updated_at to the SET clause if it&#39;s a soft delete<br> appendUpdatedAtToSetClause(db)<br><br>// Injects updated_at = now() into the SET clause<br>func appendUpdatedAtToSetClause(db *gorm.DB) {<br> updatedAt := db.Statement.Schema.LookUpField(&quot;UpdatedAt&quot;)<br> deletedAt := db.Statement.Schema.LookUpField(&quot;DeletedAt&quot;)<br><br> if db.Statement.Unscoped || updatedAt == nil || deletedAt == nil {<br>  return // Only apply to soft deletes<br> }<br><br> currentTime := db.Statement.DB.NowFunc()<br><br> // checks if the SET clause exists in db.Statement.Clauses and ensures its Expression is of type clause.Set.<br> if setClause, ok := db.Statement.Clauses[&quot;SET&quot;].Expression.(clause.Set); ok {<br>  setClause = append(setClause, clause.Assignment{<br>   Column: clause.Column{Name: updatedAtField.DBName}, Value: currentTime,<br>  })<br>  db.Statement.AddClause(setClause)<br> } else {<br>  // The SET clause doesn&#39;t exist in db.Statement.Clauses when no column-value assignments have been added to the query yet.<br>  db.Statement.Clauses[&quot;SET&quot;] = clause.Clause{<br>   Expression: clause.Set{<br>    {<br>     Column: clause.Column{Name: updatedAtField.DBName}, Value: currentTime,<br>    },<br>   },<br>  }<br> }<br>}</pre><p><strong>Register the Custom Callback</strong></p><p>To use this callback in your code:</p><pre>func main() {<br>    db, err := gorm.Open(postgres.Open(&quot;dsn&quot;), &amp;gorm.Config{})<br>    if err != nil {<br>        panic(&quot;failed to connect database&quot;)<br>    }<br><br>    // Register our custom callback to replace the default GORM delete<br>    db.Callback().Delete().Replace(&quot;gorm:delete&quot;, DeleteCallback)<br><br>    // Now when you call db.Delete(...), it will update &#39;updated_at&#39; as well<br>}</pre><h4><strong>3. Benefits &amp; Best Practices</strong></h4><p>• <strong>Improved Data Integrity:</strong> Each modification (including soft deletes) updates updated_at. This helps maintain a clear record for lifecycle events, ensuring no mismatches exist between deleted_at and updated_at.</p><p>• <strong>Enhanced Auditing:</strong> Teams can rely on the updated_at column to detect all changes. This makes incremental data extraction (for analytics, data warehousing, or compliance) far more straightforward.</p><p>• <strong>Meets Requirements of the Data Team:</strong> Many data engineering teams extract only newly changed rows using the highest updated_at value, ensuring a smooth and optimized ETL/ELT process.</p><p>• <strong>Consistency with Rest of the Model:</strong> If you treat <em>any</em> record alteration as a legitimate “update,” then a soft delete should also reflect the moment that “update” took place. This is really where our approach differs from the default GORM approach. We view the updated_at column as a system column, and they view it as an application column which for that, the data didnt’ get an update.</p><p>• <strong>Reduced Manual Intervention and Cognitive Load:</strong> Automating the update of updated_at via a custom GORM callback eliminates the need for manual timestamp handling on each delete operation, significantly reducing the potential for human error and simplifying code maintenance.</p><h4><strong>4. Transactions &amp; Data Safety</strong></h4><p>Your custom callback works inside the same <strong>transaction</strong> context as the GORM operation. If you’re using transactions (e.g., multiple statements that should succeed or fail together), the updated_at change and delete statement commit or roll back together. This ensures:</p><p>• <strong>Atomicity</strong>: Either everything persists, or nothing does.</p><p>• <strong>Reduce Risk:</strong> Avoids partial updates that could leave updated_at changed while the record wasn’t actually deleted (or vice versa).</p><h4><strong>5. Potential Considerations</strong></h4><p>a. <strong>Performance Overhead<br></strong>Appending updated_at to every delete adds minimal overhead. However, in high-throughput environments or massive bulk deletes, benchmark to ensure the overhead is acceptable.</p><p>b. <strong>Handling Unscoped Deletes:</strong><br>The custom callback described in this article specifically applies to soft delete operations (when the record’s DeletedAt field is updated rather than removed). If your application performs an unscoped (hard) delete using db.Unscoped().Delete(...), your callback logic won’t execute because GORM bypasses the soft delete mechanism entirely.<br>This means updated_at won’t be automatically updated during hard deletes, which makes sense since it’ll be removed with the rest of the record. You should explicitly consider and handle this scenario separately if your audit or data integrity requirements also extend to physical deletions.</p><p>c. <strong>Database Compatibility<br></strong>Although this solution is database-agnostic, it’s good to test thoroughly with your specific DB engine (MySQL, PostgreSQL, SQLite, etc.).</p><p>d. <strong>Testing<br></strong>• Write unit tests and integration tests to confirm updated_at is indeed updated whenever you soft-delete a record.<br>• Verify that no unexpected interactions occur with other callbacks.</p><h4><strong>6. Conclusion</strong></h4><p>By customizing GORM’s delete behavior, you ensure that <strong>soft deletes</strong> are properly reflected in your timestamp columns. This small tweak can yield significant benefits for auditing, data governance, and especially for data teams relying on consistent timestamps to track incremental changes.</p><p>Updating the updated_at column during delete actions <strong>closes the gap</strong> in standard GORM behavior and aligns your data model with real-world needs, where any change, including a deletion, is recognized as an “update” to the state of that record.</p><p>If you’ve encountered issues with missing deletes in your analytics or you’re simply keen on better data management practices, give this approach a try and watch your data pipelines become more robust!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7da7817f796a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tailor-tech/gorm-soft-delete-how-to-update-the-updated-at-field-automatically-7da7817f796a">GORM Soft Delete: How to Update the updated_at Field Automatically</a> was originally published in <a href="https://medium.com/tailor-tech">Tailor Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>