refactor(author): derive and store author sort name on save (#1897)

This commit is contained in:
Zach
2026-07-03 14:49:25 -04:00
committed by GitHub
parent 983804137f
commit 55b9d34c91
7 changed files with 424 additions and 0 deletions
@@ -2,6 +2,7 @@ package org.booklore.model.entity;
import jakarta.persistence.*;
import lombok.*;
import org.booklore.util.AuthorSortName;
import org.hibernate.Hibernate;
import org.hibernate.annotations.BatchSize;
@@ -25,6 +26,12 @@ public class AuthorEntity {
@Column(name = "name")
private String name;
@Column(name = "sort_name")
private String sortName;
@Column(name = "sort_name_locked", nullable = false)
private boolean sortNameLocked;
@Column(name = "description", columnDefinition = "TEXT")
private String description;
@@ -48,6 +55,14 @@ public class AuthorEntity {
@Builder.Default
private Set<BookMetadataEntity> bookMetadataEntityList = new HashSet<>();
@PrePersist
@PreUpdate
public void computeSortName() {
if (!sortNameLocked) {
sortName = AuthorSortName.compute(name);
}
}
@Override
public final boolean equals(Object o) {
if (this == o) return true;
@@ -20,6 +20,7 @@ public class AppMigrationStartup {
private final PopulateSearchTextMigration populateSearchTextMigration;
private final GenerateCoverHashMigration generateCoverHashMigration;
private final MigrateProgressToFileProgressMigration migrateProgressToFileProgressMigration;
private final PopulateAuthorSortNameMigration populateAuthorSortNameMigration;
@EventListener(ApplicationReadyEvent.class)
public void runMigrationsOnce() {
@@ -32,5 +33,6 @@ public class AppMigrationStartup {
appMigrationService.executeMigration(populateSearchTextMigration);
appMigrationService.executeMigration(generateCoverHashMigration);
appMigrationService.executeMigration(migrateProgressToFileProgressMigration);
appMigrationService.executeMigration(populateAuthorSortNameMigration);
}
}
@@ -0,0 +1,68 @@
package org.booklore.service.migration.migrations;
import org.booklore.repository.AuthorRepository;
import org.booklore.service.migration.Migration;
import org.booklore.util.AuthorSortName;
import jakarta.persistence.EntityManager;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Component;
@Slf4j
@Component
@RequiredArgsConstructor
public class PopulateAuthorSortNameMigration implements Migration {
private final AuthorRepository authorRepository;
private final EntityManager entityManager;
@Override
public String getKey() {
return "populateAuthorSortName";
}
@Override
public String getDescription() {
return "Populate sort_name column for all authors";
}
@Override
public void execute() {
log.info("Starting migration: {}", getKey());
var batchSize = 1000;
var processedCount = 0;
var page = 0;
while (true) {
// Stable id ordering keeps offset paging consistent as rows are updated each batch.
var authors = authorRepository.findAll(PageRequest.of(page, batchSize, Sort.by("id"))).getContent();
if (authors.isEmpty()) {
break;
}
for (var author : authors) {
if (!author.isSortNameLocked()) {
author.setSortName(AuthorSortName.compute(author.getName()));
}
}
authorRepository.saveAll(authors);
processedCount += authors.size();
log.info("Migration progress: {} authors processed", processedCount);
// Flush and detach the batch so the persistence context does not grow across the scan.
entityManager.flush();
entityManager.clear();
if (authors.size() < batchSize) {
break;
}
page++;
}
log.info("Completed migration '{}'. Total authors processed: {}", getKey(), processedCount);
}
}
@@ -0,0 +1,153 @@
package org.booklore.util;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
/**
* Derives a sortable form of an author name ("Firstname Lastname" -> "Lastname, Firstname").
*
* <p>Adapted from Calibre's {@code author_to_author_sort}, written by Kovid Goyal and the Calibre
* contributors. Calibre is licensed under GPL-3.0, compatible with this project's AGPL-3.0 license.
*
* @see <a href="https://github.com/kovidgoyal/calibre/blob/v9.10.0/src/calibre/ebooks/metadata/__init__.py">calibre/ebooks/metadata/__init__.py</a>
*/
public final class AuthorSortName {
public enum CopyMethod {
// "Firstname Lastname" -> "Lastname, Firstname"
INVERT,
// Leave the name untouched
COPY,
// Invert only when the name has no comma already
COMMA,
// Invert without inserting a comma
NOCOMMA
}
public record Config(
CopyMethod copyMethod,
Set<String> prefixes,
Set<String> suffixes,
Set<String> copyWords,
boolean useSurnamePrefixes,
Set<String> surnamePrefixes
) {
public Config {
prefixes = withDotVariants(prefixes);
suffixes = withDotVariants(suffixes);
copyWords = withDotVariants(copyWords);
surnamePrefixes = lowercased(surnamePrefixes);
}
}
public static final Config DEFAULT = new Config(
CopyMethod.INVERT,
Set.of("mr", "mrs", "ms", "dr", "prof"),
Set.of("jr", "sr", "inc", "ph.d", "phd", "md", "m.d", "i", "ii", "iii", "iv", "junior", "senior"),
Set.of("agency", "corporation", "council", "committee", "inc.", "institute", "national", "society", "club", "team"),
false,
Set.of("da", "de", "der", "den", "des", "di", "du", "la", "le", "van", "von", "ter", "ten", "vande", "vanden", "vander")
);
private AuthorSortName() {
}
public static String compute(String name) {
return compute(name, DEFAULT);
}
public static String compute(String name, Config config) {
if (name == null) {
return null;
}
var trimmed = name.trim();
if (trimmed.isEmpty()) {
return trimmed;
}
var tokens = new ArrayList<>(List.of(trimmed.split("\\s+")));
if (tokens.size() < 2) {
return trimmed;
}
var lowerTokens = new HashSet<String>();
for (var token : tokens) {
lowerTokens.add(token.toLowerCase(Locale.ROOT));
}
if (config.copyMethod() == CopyMethod.COPY || intersects(lowerTokens, config.copyWords())) {
return trimmed;
}
var deque = new ArrayDeque<>(tokens);
while (!deque.isEmpty() && config.prefixes().contains(deque.peekFirst().toLowerCase(Locale.ROOT))) {
deque.removeFirst();
}
var suffix = new ArrayDeque<String>();
while (!deque.isEmpty() && config.suffixes().contains(deque.peekLast().toLowerCase(Locale.ROOT))) {
suffix.addFirst(deque.removeLast());
}
if (deque.isEmpty()) {
return trimmed;
}
var remaining = new ArrayList<>(deque);
if (config.copyMethod() == CopyMethod.COMMA && String.join(" ", remaining).contains(",")) {
return trimmed;
}
// Absorb consecutive surname prefixes into the surname, e.g. "van der Berg" stays together
while (config.useSurnamePrefixes() && remaining.size() > 1
&& config.surnamePrefixes().contains(remaining.get(remaining.size() - 2).toLowerCase(Locale.ROOT))) {
var merged = remaining.remove(remaining.size() - 2) + " " + remaining.get(remaining.size() - 1);
remaining.set(remaining.size() - 1, merged);
}
if (remaining.size() < 2) {
// Only a surname survives after stripping prefixes/suffixes
var single = new ArrayList<>(remaining);
single.addAll(suffix);
return String.join(" ", single);
}
var surname = remaining.remove(remaining.size() - 1);
var result = new ArrayList<String>();
result.add(config.copyMethod() == CopyMethod.NOCOMMA ? surname : surname + ",");
result.addAll(remaining);
result.addAll(suffix);
return String.join(" ", result);
}
private static boolean intersects(Set<String> a, Set<String> b) {
for (var value : a) {
if (b.contains(value)) {
return true;
}
}
return false;
}
private static Set<String> withDotVariants(Set<String> values) {
var result = new HashSet<String>();
for (var value : values) {
var lower = value.toLowerCase(Locale.ROOT);
var base = lower.endsWith(".") ? lower.substring(0, lower.length() - 1) : lower;
result.add(base);
result.add(base + ".");
}
return Set.copyOf(result);
}
private static Set<String> lowercased(Set<String> values) {
var result = new HashSet<String>();
for (var value : values) {
result.add(value.toLowerCase(Locale.ROOT));
}
return Set.copyOf(result);
}
}
@@ -0,0 +1,7 @@
ALTER TABLE author ADD COLUMN IF NOT EXISTS sort_name VARCHAR(255);
ALTER TABLE author ADD COLUMN IF NOT EXISTS sort_name_locked BOOLEAN NOT NULL DEFAULT FALSE;
UPDATE author SET sort_name = name
WHERE sort_name IS NULL;
CREATE INDEX IF NOT EXISTS idx_author_sort_name ON author (sort_name);
@@ -0,0 +1,62 @@
package org.booklore.model.entity;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class AuthorEntityTest {
@Test
void computesSortNameOnSaveWhenUnlocked() {
AuthorEntity author = AuthorEntity.builder().name("George Orwell").build();
author.computeSortName();
assertThat(author.getSortName()).isEqualTo("Orwell, George");
}
@Test
void preservesManualOverrideWhenLocked() {
AuthorEntity author = AuthorEntity.builder()
.name("George Orwell")
.sortName("Orwell the Great")
.sortNameLocked(true)
.build();
author.computeSortName();
assertThat(author.getSortName()).isEqualTo("Orwell the Great");
}
@Test
void leavesSortNameNullForNullName() {
AuthorEntity author = AuthorEntity.builder().build();
author.computeSortName();
assertThat(author.getSortName()).isNull();
}
@Test
void computesBlankSortNameForBlankName() {
AuthorEntity author = AuthorEntity.builder().name(" ").build();
author.computeSortName();
assertThat(author.getSortName()).isEmpty();
}
@Test
void recomputesAfterUnlocking() {
AuthorEntity author = AuthorEntity.builder()
.name("George Orwell")
.sortName("Orwell the Great")
.sortNameLocked(true)
.build();
author.setSortNameLocked(false);
author.computeSortName();
assertThat(author.getSortName()).isEqualTo("Orwell, George");
}
}
@@ -0,0 +1,117 @@
package org.booklore.util;
import org.booklore.util.AuthorSortName.Config;
import org.booklore.util.AuthorSortName.CopyMethod;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import java.util.Set;
import java.util.stream.Stream;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.params.provider.Arguments.arguments;
class AuthorSortNameTest {
private static Stream<Arguments> defaultSortNames() {
return Stream.of(
// Simple two-token names invert to "Surname, Firstname"
arguments("George Orwell", "Orwell, George"),
arguments("J.R.R. Tolkien", "Tolkien, J.R.R."),
// Multiple given names all follow the surname
arguments("John Ronald Reuel Tolkien", "Tolkien, John Ronald Reuel"),
// A single token is left untouched
arguments("Plato", "Plato"),
// Hyphenated surnames stay intact
arguments("Mary-Kate Olsen", "Olsen, Mary-Kate"),
// Surname prefixes stay with the given names when the feature is off (Calibre default)
arguments("Ludwig van Beethoven", "Beethoven, Ludwig van"),
// A trailing suffix is detached and re-appended at the end
arguments("Martin Luther King Jr.", "King, Martin Luther Jr."),
arguments("Jane Smith PhD", "Smith, Jane PhD"),
// Multiple stacked suffixes are all moved to the end, in order
arguments("Henry Williams Jr. III", "Williams, Henry Jr. III"),
// Honorific prefix and trailing suffix are both handled
arguments("Dr. Henry Jones Jr.", "Jones, Henry Jr."),
// Honorific prefixes are stripped
arguments("Dr. Seuss", "Seuss"),
// When stripping a suffix leaves a single name token, it is re-appended (no inversion)
arguments("Henry II", "Henry II"),
// When every token is a prefix/suffix, the original name is returned unchanged
arguments("Dr. Jr.", "Dr. Jr."),
// Organisation names (copywords) are copied verbatim, case-insensitively
arguments("National Geographic Society", "National Geographic Society"),
arguments("national geographic society", "national geographic society"),
// Copywords match with or without a trailing dot ("inc." set entry vs "Inc" token)
arguments("Marvel Comics Inc", "Marvel Comics Inc")
);
}
@ParameterizedTest(name = "[{index}] \"{0}\" -> \"{1}\"")
@MethodSource("defaultSortNames")
void computesDefaultSortName(String input, String expected) {
assertThat(AuthorSortName.compute(input)).isEqualTo(expected);
}
@Test
void returnsNullForNull() {
assertThat(AuthorSortName.compute(null)).isNull();
}
@Test
void returnsEmptyForBlank() {
assertThat(AuthorSortName.compute(" ")).isEmpty();
}
@Test
void trimsSurroundingWhitespace() {
assertThat(AuthorSortName.compute(" George Orwell ")).isEqualTo("Orwell, George");
}
@Test
void collapsesInternalWhitespaceAndTabs() {
assertThat(AuthorSortName.compute("Ursula\tK. Le Guin")).isEqualTo("Guin, Ursula K. Le");
}
@Test
void keepsSurnamePrefixWithSurnameWhenEnabled() {
Config config = surnamePrefixConfig();
assertThat(AuthorSortName.compute("Vincent van Gogh", config)).isEqualTo("van Gogh, Vincent");
}
@Test
void absorbsConsecutiveSurnamePrefixesWhenEnabled() {
Config config = surnamePrefixConfig();
assertThat(AuthorSortName.compute("Johannes van der Berg", config)).isEqualTo("van der Berg, Johannes");
}
@Test
void copyMethodLeavesNameUntouched() {
Config config = new Config(CopyMethod.COPY, Set.of(), Set.of(), Set.of(), false, Set.of());
assertThat(AuthorSortName.compute("George Orwell", config)).isEqualTo("George Orwell");
}
@Test
void nocommaMethodOmitsComma() {
Config config = new Config(CopyMethod.NOCOMMA, Set.of(), Set.of(), Set.of(), false, Set.of());
assertThat(AuthorSortName.compute("George Orwell", config)).isEqualTo("Orwell George");
}
@Test
void commaMethodPreservesNamesThatAlreadyContainAComma() {
Config config = new Config(CopyMethod.COMMA, Set.of(), Set.of(), Set.of(), false, Set.of());
assertThat(AuthorSortName.compute("Orwell, George", config)).isEqualTo("Orwell, George");
}
@Test
void commaMethodInvertsNamesWithoutAComma() {
Config config = new Config(CopyMethod.COMMA, Set.of(), Set.of(), Set.of(), false, Set.of());
assertThat(AuthorSortName.compute("George Orwell", config)).isEqualTo("Orwell, George");
}
private static Config surnamePrefixConfig() {
return new Config(CopyMethod.INVERT, Set.of(), Set.of(), Set.of(), true, Set.of("van", "von", "de", "der"));
}
}