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);
}
}