module CQL::ActiveRecord::SoftDeletable

Overview

The SoftDeletable module provides "paranoid" delete functionality, allowing records to be marked as deleted with a timestamp rather than being physically removed from the database.

Features

Usage

The table needs a nullable deleted_at column:

AppDB = CQL::Schema.define(:app_db, adapter: CQL::Adapter::SQLite, uri: "sqlite3://./app.db") do
  table :accounts do
    primary :id, Int64, auto_increment: true
    column :name, String
    column :deleted_at, Time, null: true
  end
end

class Account
  include CQL::ActiveRecord::Model(Int64)
  include CQL::ActiveRecord::SoftDeletable # adds property deleted_at : Time?
  db_context AppDB, :accounts

  property name : String = ""

  def initialize
  end
end

# Basic usage
account = Account.create!(name: "John")
account.delete! # Soft deletes the account (sets deleted_at)
Account.all     # Returns accounts without soft-deleted ones

# Working with soft-deleted records
Account.with_deleted.all # Returns all accounts including soft-deleted
Account.only_deleted.all # Returns only soft-deleted accounts
account.restore!         # Restores a soft-deleted account
account.force_delete!    # Permanently deletes the account

Defined in:

active_record/soft_deletable.cr