diff --git a/examples/app1/grails-app/domain/app/Customer.groovy b/examples/app1/grails-app/domain/app/Customer.groovy new file mode 100644 index 0000000..420dada --- /dev/null +++ b/examples/app1/grails-app/domain/app/Customer.groovy @@ -0,0 +1,16 @@ +package app + +// tag::customer_class[] +import grails.logical.delete.LogicalDeleteTimestamp + +class Customer implements LogicalDeleteTimestamp { + + String name + + static mapping = { + // the deletedAt property may be configured + // like any other persistent property... + deletedAt(column: 'removed_at') + } +} +// end::customer_class[] diff --git a/examples/app1/grails-app/services/app/CustomersDataService.groovy b/examples/app1/grails-app/services/app/CustomersDataService.groovy new file mode 100644 index 0000000..6dcdc42 --- /dev/null +++ b/examples/app1/grails-app/services/app/CustomersDataService.groovy @@ -0,0 +1,14 @@ +package app + +import grails.logical.delete.annotations.WithDeleted + +import grails.gorm.services.Service + +@Service(Customer) +interface CustomersDataService { + + List listCustomers() + + @WithDeleted + List listCustomersWithDeleted() +} diff --git a/examples/app1/src/integration-test/groovy/grails/logical/delete/LogicalDeleteTimestampSpec.groovy b/examples/app1/src/integration-test/groovy/grails/logical/delete/LogicalDeleteTimestampSpec.groovy new file mode 100644 index 0000000..0030df8 --- /dev/null +++ b/examples/app1/src/integration-test/groovy/grails/logical/delete/LogicalDeleteTimestampSpec.groovy @@ -0,0 +1,214 @@ +package grails.logical.delete + +import java.time.Instant +import java.time.temporal.ChronoUnit + +import app.Customer +import app.CustomersDataService +import org.springframework.beans.factory.annotation.Autowired +import spock.lang.Narrative +import spock.lang.Specification +import spock.lang.Title + +import grails.gorm.transactions.Rollback +import grails.testing.mixin.integration.Integration + +@Integration +@Title('Verify LogicalDeleteTimestamp operations') +@Narrative('This specification focuses on logical deletes recorded in a deletedAt timestamp.') +class LogicalDeleteTimestampSpec extends Specification { + + @Autowired + CustomersDataService dataService + + Customer acme + Customer globex + Customer initech + + // Called from each feature, so the customers are created in its rolled back transaction + private void createCustomers() { + acme = new Customer(name: 'Acme').save(flush: true) + globex = new Customer(name: 'Globex').save(flush: true) + initech = new Customer(name: 'Initech').save(flush: true) + } + + @Rollback + void 'delete() records when the entity was deleted'() { + given: 'the earliest time the deletion may be recorded at' + createCustomers() + def before = Instant.now().truncatedTo(ChronoUnit.SECONDS) + + expect: 'the customer is not deleted' + acme.deletedAt == null + + when: 'deleting the customer logically' + // tag::delete_timestamp[] + acme.delete(flush: true) + // end::delete_timestamp[] + Customer.withSession { it.clear() } + def customer = Customer.withDeleted { Customer.get(acme.id) } as Customer + + then: 'the deletion time is recorded' + customer.deletedAt != null + !customer.deletedAt.isBefore(before) + !customer.deletedAt.isAfter(Instant.now()) + } + + @Rollback + void 'deleting an entity again keeps the original deletion time'() { + given: 'a customer that was deleted in the past' + createCustomers() + def deletedAt = Instant.parse('2020-01-01T00:00:00Z') + acme.deletedAt = deletedAt + acme.save(flush: true) + + when: 'deleting the customer again' + acme.delete() + acme.delete(flush: true) + Customer.withSession { it.clear() } + def customer = Customer.withDeleted { Customer.get(acme.id) } as Customer + + then: 'the original deletion time is kept' + customer.deletedAt == deletedAt + } + + @Rollback + void 'logically deleted entities are excluded when retrieved by id'() { + given: + createCustomers() + + when: + acme.delete(flush: true) + + then: 'the deleted customer is excluded' + Customer.get(acme.id) == null + Customer.read(acme.id) == null + Customer.load(acme.id) == null + Customer.proxy(acme.id) == null + + and: 'other customers are still found' + Customer.get(globex.id).name == 'Globex' + + and: 'the deleted customer is found with withDeleted' + Customer.withDeleted { Customer.get(acme.id) } + Customer.withDeleted { Customer.read(acme.id) } + Customer.withDeleted { (Customer.load(acme.id) as Customer).name } == 'Acme' + Customer.withDeleted { (Customer.proxy(acme.id) as Customer).name } == 'Acme' + } + + @Rollback + void 'logically deleted entities are excluded from query results'() { + given: + createCustomers() + + when: 'deleting two of the customers' + acme.delete(flush: true) + globex.delete(flush: true) + + and: 'querying for all customers in different ways' + def listed = Customer.list() + def foundAll = Customer.findAll() + def foundByName = Customer.findByName('Acme') + def foundAllByName = Customer.findAllByNameInList(['Acme', 'Globex', 'Initech']) + // tag::where_timestamp[] + def whereResults = Customer.where { + name == 'Acme' || name == 'Initech' + }.list() + // end::where_timestamp[] + def foundAllWhere = Customer.findAll { name == 'Globex' || name == 'Initech' } + def criteriaResults = Customer.createCriteria().list { inList('name', ['Acme', 'Globex', 'Initech']) } + def count = Customer.createCriteria().get { projections { count() } } as int + + then: 'only the customer that is not deleted is found' + listed*.name == ['Initech'] + foundAll*.name == ['Initech'] + foundByName == null + foundAllByName*.name == ['Initech'] + whereResults*.name == ['Initech'] + foundAllWhere*.name == ['Initech'] + criteriaResults*.name == ['Initech'] + count == 1 + } + + @Rollback + void 'withDeleted includes logically deleted entities in query results'() { + given: + createCustomers() + + when: 'deleting a customer' + acme.delete(flush: true) + + and: 'querying with withDeleted' + def listed = Customer.withDeleted { Customer.list() } as List + def foundByName = Customer.withDeleted { Customer.findByName('Acme') } + def whereResults = Customer.withDeleted { Customer.where { name == 'Acme' }.list() } as List + def criteriaResults = Customer.withDeleted { + Customer.createCriteria().list { eq('name', 'Acme') } + } as List + + then: 'the deleted customer is included' + listed.size() == 3 + foundByName + whereResults*.name == ['Acme'] + criteriaResults*.name == ['Acme'] + } + + @Rollback + void 'undelete() clears the deletion time'() { + given: + createCustomers() + acme.delete(flush: true) + + when: + def customer = Customer.withDeleted { Customer.get(acme.id) } as Customer + customer.undelete(flush: true) + + then: + customer.deletedAt == null + Customer.get(acme.id) + Customer.list().size() == 3 + } + + @Rollback + void 'delete(hard: true) removes the entity'() { + given: + createCustomers() + + when: + acme.delete(hard: true, flush: true) + + then: + Customer.withDeleted { Customer.get(acme.id) } == null + Customer.withDeleted { Customer.list() }.size() == 2 + } + + @Rollback + void 'the deletedAt property is mapped like any other property'() { + given: + createCustomers() + + when: + acme.delete(flush: true) + def deletedRows = Customer.withSession { session -> + (session as org.hibernate.Session) + .createNativeQuery('select count(*) from customer where removed_at is not null') + .singleResult + } + + then: 'the deletion time is stored in the mapped column' + (deletedRows as Number).longValue() == 1 + } + + @Rollback + void '@WithDeleted on Data Service methods includes logically deleted entities'() { + given: + createCustomers() + + when: + acme.delete(flush: true) + + then: + dataService.listCustomers()*.name.sort() == ['Globex', 'Initech'] + dataService.listCustomersWithDeleted()*.name.sort() == ['Acme', 'Globex', 'Initech'] + } +} diff --git a/plugin/src/docs/index.adoc b/plugin/src/docs/index.adoc index 0601e75..7232057 100755 --- a/plugin/src/docs/index.adoc +++ b/plugin/src/docs/index.adoc @@ -144,12 +144,49 @@ This is particularly useful when working with GORM Data Services or other classe include::{examples}/app1/grails-app/services/app/PeopleDataService.groovy[tags=peopleDataService,indent=0] ---- +=== Recording When an Entity Was Deleted + +To record **when** an entity was logically deleted instead of only **whether** it was, implement the +link:../api/grails/logical/delete/LogicalDeleteTimestamp.html[LogicalDeleteTimestamp] trait instead of `LogicalDelete`. + +The trait adds a persistent, nullable `java.time.Instant` property named `deletedAt`. +An entity is considered __logically deleted__ when `deletedAt` is set, and not deleted when it is `null`. + +[source,groovy] +---- +include::{examples}/app1/grails-app/domain/app/Customer.groovy[tags=customer_class,indent=0] +---- + +Calling `delete()` sets `deletedAt` to the current time, and `undelete()` sets it back to `null`. +Deleting an entity that is already logically deleted keeps its original deletion time. +As with `LogicalDelete`, `delete(hard: true)` physically deletes the record. + +[source,groovy] +---- +include::{examples}/app1/src/integration-test/groovy/grails/logical/delete/LogicalDeleteTimestampSpec.groovy[tags=delete_timestamp,indent=0] +---- + +Everything else works the same way as for `LogicalDelete`: queries exclude logically deleted records by default, +and `withDeleted` and the `@WithDeleted` annotation include them. For example, this query only returns +`Initech` if `Acme` has been logically deleted: + +[source,groovy] +---- +include::{examples}/app1/src/integration-test/groovy/grails/logical/delete/LogicalDeleteTimestampSpec.groovy[tags=where_timestamp,indent=0] +---- + +NOTE: Persistent properties are nullable by default in Grails 8. If your application makes them non-nullable by default, +with `grails.gorm.default.nullable = false` or a `'*'(nullable: false)` default constraint, +add `deletedAt(nullable: true)` to the `constraints` of the domain class. + == Implementation Details This section provides a brief overview of the internal implementation of the **Grails Logical Delete** plugin. The link:../api/grails/logical/delete/LogicalDelete.html[LogicalDelete] trait defines the `deleted` property and overrides core persistence methods to implement **soft deletion** and **query filtering** behavior. +The link:../api/grails/logical/delete/LogicalDeleteTimestamp.html[LogicalDeleteTimestamp] trait does the same +with the `deletedAt` property. The link:../api/grails/logical/delete/PreQueryListener.html[PreQueryListener] listens for query events and modifies the query to automatically **exclude logically deleted records**. diff --git a/plugin/src/main/groovy/grails/logical/delete/LogicalDeleteTimestamp.groovy b/plugin/src/main/groovy/grails/logical/delete/LogicalDeleteTimestamp.groovy new file mode 100644 index 0000000..e78c43d --- /dev/null +++ b/plugin/src/main/groovy/grails/logical/delete/LogicalDeleteTimestamp.groovy @@ -0,0 +1,253 @@ +/* + * Copyright 2026 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package grails.logical.delete + +import java.time.Instant + +import groovy.transform.CompileStatic + +import grails.gorm.DetachedCriteria +import org.grails.datastore.gorm.GormEnhancer +import org.grails.datastore.gorm.GormEntity +import org.grails.datastore.gorm.GormStaticApi + +/** + * Adds soft delete capabilities to a domain class, recording when an entity + * was logically deleted in a nullable {@code deletedAt} timestamp. + * + *

An entity is considered logically deleted when {@code deletedAt} is set, + * and is excluded from query results by default. + */ +@CompileStatic +trait LogicalDeleteTimestamp extends GormEntity { + + Instant deletedAt + + /** + * Executes the given closure with soft-deleted records included in queries. + * + * @param closure The closure to execute + * @return The result of the closure execution + */ + static Object withDeleted(Closure closure) { + def initialValue = this.shouldExcludeDeleted() + try { + this.setExcludeDeleted(false) + return closure.call() + } finally { + this.setExcludeDeleted(initialValue) + } + } + + /** + * Retrieves an entity by its identifier, excluding soft-deleted records by default. + * + * @param id The identifier of the entity + * @return The entity instance or null if not found + */ + static D get(Serializable id) { + (D) (this.shouldExcludeDeleted() ? + this.notDeletedWithId(id).get() : + this.currentGormStaticApi().get(id)) + } + + /** + * Reads an entity by its identifier, excluding soft-deleted records by default. + * + * @param id The identifier of the entity + * @return The entity instance or null if not found + */ + static D read(Serializable id) { + (D) (this.shouldExcludeDeleted() ? + this.notDeletedWithId(id).get() : + this.currentGormStaticApi().read(id)) + } + + /** + * Loads an entity by its identifier, excluding soft-deleted records by default. + * + * @param id The identifier of the entity + * @return The entity instance or null if not found + */ + static D load(Serializable id) { + (D) (this.shouldExcludeDeleted() ? + this.notDeletedWithId(id).get() : + this.currentGormStaticApi().load(id)) + } + + /** + * Proxies an entity by its identifier, excluding soft-deleted records by default. + * + * @param id The identifier of the entity + * @return The proxy instance of the entity + */ + static D proxy(Serializable id) { + (D) (this.shouldExcludeDeleted() ? + this.notDeletedWithId(id).get() : + this.currentGormStaticApi().proxy(id)) + } + + /** + * Finds all entities, excluding soft-deleted records by default. + * + * @param params The query parameters + * @return A list of entity instances + */ + static List findAll(Map params = [:]) { + (List) (this.shouldExcludeDeleted() ? + new DetachedCriteria(this).build { + isNull('deletedAt') + }.list(params) : + this.currentGormStaticApi().findAll(params)) + } + + /** + * Lists all entities, excluding soft-deleted records by default. + * + * @param params The query parameters + * @return A list of entity instances + */ + static List list(Map params = [:]) { + (List) (this.shouldExcludeDeleted() ? + new DetachedCriteria(this).build { + isNull('deletedAt') + }.list(params) : + this.currentGormStaticApi().list(params)) + } + + /** + * Creates a DetachedCriteria instance, excluding soft-deleted records by default. + * + * @return A DetachedCriteria instance + */ + static DetachedCriteria createCriteria() { + if (this.shouldExcludeDeleted()) { + return new DetachedCriteria(this).build { + isNull('deletedAt') + } + } + new DetachedCriteria(this) + } + + /** + * Marks the entity as logically deleted, setting {@code deletedAt} to the current time. + * An entity that is already logically deleted keeps its original deletion time. + */ + void delete() { + markDeletedNow() + save() + } + + /** + * Marks the entity as logically deleted or physically deletes it + * based on the parameters. An entity that is already logically deleted + * keeps its original deletion time. + * + * @param params The parameters to control saving and deletion behavior. + * Use 'hard: true' to physically delete the entity. + */ + void delete(Map params) { + if (params?.hard) { + super.delete(params) + } else { + markDeletedNow() + save(params) + } + } + + /** + * Undeletes the entity by clearing {@code deletedAt}. + */ + void undelete() { + markDeleted(null) + save() + } + + /** + * Undeletes the entity by clearing {@code deletedAt} with additional parameters. + * + * @param params The parameters for saving the entity. + */ + void undelete(Map params) { + markDeleted(null) + save(params) + } + + /** + * Sets the deletion timestamp of the entity to the current time, + * unless it is already logically deleted. + */ + private void markDeletedNow() { + if (deletedAt == null) { + markDeleted(Instant.now()) + } + } + + /** + * Sets the deletion timestamp of the entity. + * + * @param timestamp The time the entity was deleted, + * or {@code null} to mark it as not deleted. + */ + private void markDeleted(Instant timestamp) { + markDirty('deletedAt', timestamp, deletedAt) + deletedAt = timestamp + } + + /** + * Checks if soft-deleted records should be excluded from queries. + * + * @return {@code true} if soft-deleted records should be excluded, + * {@code false} otherwise. + */ + private static boolean shouldExcludeDeleted() { + grails.logical.delete.PreQueryListener.EXCLUDE_SOFT_DELETED_FLAG.get() + } + + /** + * Sets the flag whether soft-deleted records should be excluded + * for any queries executed in this thread. + * + * @param value {@code true} to exclude soft-deleted records, + * {@code false} to include them. + */ + private static void setExcludeDeleted(boolean value) { + grails.logical.delete.PreQueryListener.EXCLUDE_SOFT_DELETED_FLAG.set(value) + } + + /** + * Retrieves the current GormStaticApi for the domain class. + * + * @return The GormStaticApi instance. + */ + private static GormStaticApi currentGormStaticApi() { + (GormStaticApi) GormEnhancer.findStaticApi(this) + } + + /** + * Creates a DetachedCriteria to find an entity by its ID, + * excluding soft-deleted records. + * + * @param id The identifier of the entity. + * @return A DetachedCriteria instance for the query. + */ + private static DetachedCriteria notDeletedWithId(Serializable id) { + new DetachedCriteria(this).build { + eq('id', id) + isNull('deletedAt') + } + } +} diff --git a/plugin/src/main/groovy/grails/logical/delete/PreQueryListener.groovy b/plugin/src/main/groovy/grails/logical/delete/PreQueryListener.groovy index 02eacda..ddcf524 100644 --- a/plugin/src/main/groovy/grails/logical/delete/PreQueryListener.groovy +++ b/plugin/src/main/groovy/grails/logical/delete/PreQueryListener.groovy @@ -32,24 +32,41 @@ class PreQueryListener implements ApplicationListener { private static final Query.Criterion NOT_DELETED = new Query.Equals('deleted', false) + private static final Query.Criterion NOT_DELETED_AT = + new Query.IsNull('deletedAt') + @Override void onApplicationEvent(PreQueryEvent event) { try { def query = event.query def entity = query.entity - if (LogicalDelete.isAssignableFrom(entity.javaClass)) { + def notDeleted = notDeletedCriterion(entity.javaClass) + if (notDeleted) { def shouldExcludeDeleted = EXCLUDE_SOFT_DELETED_FLAG.get() log.debug( - 'Entity {} implements LogicalDelete, excluding soft deletes from query results: {}', + 'Entity {} supports logical delete, excluding soft deletes from query results: {}', entity, shouldExcludeDeleted ) if (shouldExcludeDeleted) { - query.add(NOT_DELETED) + query.add(notDeleted) } } } catch (Exception e) { log.error(e.message) } } + + /** + * Returns the criterion matching entities that are not logically deleted. + * + * @param entityClass The class of the queried entity + * @return The criterion, or {@code null} if the entity does not support logical delete + */ + private static Query.Criterion notDeletedCriterion(Class entityClass) { + if (LogicalDelete.isAssignableFrom(entityClass)) { + return NOT_DELETED + } + LogicalDeleteTimestamp.isAssignableFrom(entityClass) ? NOT_DELETED_AT : null + } }