在 SQLite 中处理过期记录删除的首选方法

Preferred way to approach expired records delition in SQLite

数据库中有 3 个 table -- StudentsCoursesProfessors。 每个学生都有 activation_deadline 列,激活时设置为 NULL。我需要一些机制来定期删除 activation_deadline 逾期的学生(并防止已经“过期”的学生被激活)。

目前我通过三个单独的触发器(如 there are no database or server level triggers in SQLite)为 Students table。

一个 UPDATE:

CREATE TRIGGER Remove_Unactivated_Students_Update
BEFORE UPDATE
ON Students
FOR EACH ROW
BEGIN
    DELETE FROM Students
    WHERE (activation_deadline IS NOT NULL) AND (activation_deadline <= strftime('%s', 'now'));
END;

一个 INSERT:

CREATE TRIGGER Remove_Unactivated_Students_Insert
BEFORE INSERT
ON Students
FOR EACH ROW
BEGIN
    DELETE FROM Students
    WHERE (activation_deadline IS NOT NULL) AND (activation_deadline <= strftime('%s', 'now'));
END;

还有一个 DELETE:

CREATE TRIGGER Remove_Unactivated_Students_Delete
AFTER DELETE
ON Students
FOR EACH ROW
BEGIN
    DELETE FROM Students
    WHERE (activation_deadline IS NOT NULL) AND (activation_deadline <= strftime('%s', 'now'));
END;

另一种方法是向后端添加一些代码,这将在执行对数据库的任何其他查询之前检查并删除过期记录(尽管这会增加数据库调用量,这并不好)。

在这种情况下,哪种方法(在 数据库触发器或后端 中保留 'expired' 记录删除逻辑是首选方法,为什么?各自的缺点和优点是什么?

SQLite 是一个 serverless DBMS,你不能 define/schedule 任务或工作。

您的要求应该在应用程序级别得到处理,您可以在其中定义每日或每周作业以删除 expired 名学生。

这只涉及执行 1 个非常简单和快速的 DELETE 语句,每个 day/week:

DELETE FROM Students WHERE activation_deadline <= strftime('%s', 'now');

注意条件activation_deadline IS NOT NULLactivation_deadline <= strftime('%s', 'now')覆盖了,所以不需要

任何涉及多个触发器的解决方案都是不可能的,因为它会给 table 上的任何简单 INSERT/DELETE/UPDATE 操作增加不必要的开销.