Implement Soft Deletes

This guide shows you how to implement soft deletes so records are marked as deleted rather than permanently removed.

Prerequisites

Your table needs a deleted_at timestamp column:

schema.table :users do
  primary :id, Int64, auto_increment: true
  column :name, String
  column :deleted_at, Time, null: true
  timestamps
end
schema.users.create!

Enable Soft Deletes

Include the SoftDeletable module in your model:

struct User
  include CQL::ActiveRecord::Model(Int64)
  include CQL::ActiveRecord::SoftDeletable

  db_context MyDB, :users

  property id : Int64?
  property name : String
  property created_at : Time?
  property updated_at : Time?
  # deleted_at is handled automatically

  def initialize(@name : String)
  end
end

Soft Delete Records

Delete a Single Record

Delete by ID

Delete by Attributes

Delete All Records

Restore Records

Restore a Single Record

Restore by ID

Restore All Deleted Records

Query Records

By default, queries exclude soft-deleted records:

Include Deleted Records

Query Only Deleted Records

Permanently Delete

To actually remove records from the database:

Add Index for Performance

Add an index on the deleted_at column:

Cleanup Old Records

Create a job to permanently delete old soft-deleted records:

Cascade Soft Deletes

Soft delete related records when a parent is deleted:

Verify It Works

Last updated

Was this helpful?