--- /dev/null
+/**
+ * Delete circ history rows for patrons who disabled circ history
+ * tracking between the initial migration and when the updated
+ * circ history code was deployed.
+ */
+
+BEGIN;
+
+SET STATEMENT_TIMEOUT = 0;
+
+WITH delete_history_usrs AS (
+ SELECT DISTINCT(auch.usr) AS usr_id
+ FROM action.usr_circ_history auch
+ WHERE NOT EXISTS(
+ SELECT TRUE FROM actor.usr_setting set
+ WHERE set.usr = auch.usr
+ AND set.name ~ '^history.circ.retention_'
+ )
+) DELETE FROM action.usr_circ_history
+ WHERE usr IN (SELECT usr_id FROM delete_history_usrs);
+
+--ROLLBACK;
+COMMIT;
+