Add support for @Schema and @Migrate annotations to declare storage record schema versions and migrations.

This commit is contained in:
Overlord committed 2026-10-07 14:47:57 +02:00
1 parent 1664bb6f28
commit b10504e9af
8 files changed
+326 -10

No files matched your search

+17
View File
@@ -399,6 +399,23 @@ Table<Balance> balances = this.storage().define("balances", Balance.class)
.open();
```
The same on the record (`dev.overlord.zomboidforge.api.annotations`), so `table(...)` is enough:
```java
@Schema(version = 2)
record Balance(long coins, @Nullable Instant lastPaid)
{
@Migrate(from = 1)
static Balance fromV1(Row row) { return new Balance(row.getLong("coins"), null); }
}
Table<Balance> balances = this.storage().table("balances", Balance.class);
```
A `@Migrate` method is static, takes a `Row`, returns the record, and may be private. `define`
starts from the annotations: `version(...)` replaces the `@Schema` version, and `migrate(...)`
adds migrations. Each version has one migration at most; a second one throws.
Things to know:
1. Storage calls block. On the main thread they are only allowed during `onLoad`; once the
@@ -0,0 +1,26 @@
package dev.overlord.zomboidforge.api.annotations;
import dev.overlord.zomboidforge.api.storage.Row;
import dev.overlord.zomboidforge.api.storage.TableDefinition;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* A migration of a storage record, as {@link TableDefinition#migrate} adds one: turns a row stored
* with schema version {@link #from} into the record. Declared in the record itself, as a static
* method with one {@link Row} parameter that returns the record; it may be private. A record has
* at most one migration per version, whether from this annotation or from
* {@link TableDefinition#migrate}. See {@link Schema}.
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Migrate
{
/** The stored schema version this method migrates from; at least 1. */
int from();
}
@@ -0,0 +1,35 @@
package dev.overlord.zomboidforge.api.annotations;
import dev.overlord.zomboidforge.api.storage.ModStorage;
import dev.overlord.zomboidforge.api.storage.TableDefinition;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* The schema version of a storage record, read by {@link ModStorage#table} and
* {@link ModStorage#define}; {@link TableDefinition#version} overrides it. Records without it
* have version 1. The migrations from older versions are the record's {@link Migrate} methods.
*
* <pre>{@code
* @Schema(version = 2)
* record Balance(long coins, @Nullable Instant lastPaid)
* {
* @Migrate(from = 1)
* static Balance fromV1(Row row) {
* return new Balance(row.getLong("coins"), null);
* }
* }
* }</pre>
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Schema
{
/** At least 1. */
int version();
}
@@ -1,5 +1,8 @@
package dev.overlord.zomboidforge.api.storage;
import dev.overlord.zomboidforge.api.annotations.Migrate;
import dev.overlord.zomboidforge.api.annotations.Schema;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Blocking;
@@ -22,11 +25,23 @@ import java.util.function.Supplier;
@ApiStatus.NonExtendable
public interface ModStorage
{
/** Opens the table {@code name} with schema version 1 and no migrations. */
/**
* Opens the table {@code name} with the schema version and migrations that {@code type}
* declares with {@link Schema} and {@link Migrate}; without them, version 1 and no migrations.
*
* @throws IllegalArgumentException when the name, or a {@link Schema} or {@link Migrate} of
* {@code type}, is invalid
*/
@Blocking
<R extends Record> Table<R> table(String name, Class<R> type);
/** A table with a schema version and migrations; see {@link TableDefinition}. */
/**
* A table to open with a schema version and migrations, starting from those of
* {@link Schema} and {@link Migrate} on {@code type}; see {@link TableDefinition}.
*
* @throws IllegalArgumentException when the name, or a {@link Schema} or {@link Migrate} of
* {@code type}, is invalid
*/
<R extends Record> TableDefinition<R> define(String name, Class<R> type);
/**
@@ -1,5 +1,8 @@
package dev.overlord.zomboidforge.api.storage;
import dev.overlord.zomboidforge.api.annotations.Migrate;
import dev.overlord.zomboidforge.api.annotations.Schema;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Blocking;
import org.jetbrains.annotations.Range;
@@ -7,7 +10,8 @@ import org.jetbrains.annotations.Range;
import java.util.function.Function;
/**
* A table to open with a schema version and migrations:
* A table to open with a schema version and migrations. It starts from the record's
* {@link Schema} and {@link Migrate} methods, if any; the calls below add to them:
*
* <pre>{@code
* Table<Balance> balances = this.storage().define("balances", Balance.class)
@@ -19,13 +23,16 @@ import java.util.function.Function;
@ApiStatus.NonExtendable
public interface TableDefinition<R extends Record>
{
/** Schema version of the record, at least 1. Default: 1. */
/** Schema version of the record, at least 1. Default: the record's {@link Schema}, or 1. */
TableDefinition<R> version(@Range(from = 1, to = Integer.MAX_VALUE) int version);
/**
* How to turn a row stored with schema version {@code from} into the current record. Needed
* when the stored version is older than {@link #version} or the record changed in a way that
* cannot be applied without data.
*
* @throws IllegalArgumentException when a migration from {@code from} exists already, also one
* from a {@link Migrate} method of the record
*/
TableDefinition<R> migrate(int from, Function<Row, R> migration);
@@ -36,6 +36,9 @@ import java.util.stream.Collectors;
* <li>a new primitive component, a changed type, or a different schema version needs a
* migration from the stored version, which rebuilds the table in one transaction.</li>
* </ul>
*
* The schema version and the migrations come from the record ({@link RecordSchema}), and the
* calls of {@code TableDefinition} add to them.
*/
public final class ModTables implements ModStorage
{
@@ -110,7 +113,7 @@ public final class ModTables implements ModStorage
if (name.length() > ModTables.NAME_MAX_LENGTH || !RecordCodec.NAME.matcher(name).matches())
throw new IllegalArgumentException("'" + name + "' is not a valid table name: lowercase letters, digits, and single underscores, at most " + ModTables.NAME_MAX_LENGTH + " characters.");
return new Definition<>(name, type);
return new Definition<>(name, type, RecordSchema.of(type));
}
@Override
@@ -124,12 +127,16 @@ public final class ModTables implements ModStorage
private final String name;
private final Class<R> type;
private final Map<Integer, Function<Row, R>> migrations = new HashMap<>();
private int version = 1;
private int version;
private Definition(String name, Class<R> type)
/** @param declared the record's {@code @Schema} and {@code @Migrate} methods, which the builder calls add to */
private Definition(String name, Class<R> type, RecordSchema<R> declared)
{
this.name = name;
this.type = type;
this.name = name;
this.type = type;
this.version = declared.version();
this.migrations.putAll(declared.migrations());
}
@Override
@@ -144,7 +151,11 @@ public final class ModTables implements ModStorage
@Override
public TableDefinition<R> migrate(int from, Function<Row, R> migration)
{
this.migrations.put(from, Objects.requireNonNull(migration, "migration"));
Objects.requireNonNull(migration, "migration");
if (this.migrations.putIfAbsent(from, migration) != null)
throw new IllegalArgumentException("'" + this.type.getName() + "' has a migration from version " + from + " already, from @Migrate or migrate().");
return this;
}
@@ -0,0 +1,102 @@
package dev.overlord.zomboidforge.core.storage;
import dev.overlord.zomboidforge.api.annotations.Migrate;
import dev.overlord.zomboidforge.api.annotations.Schema;
import dev.overlord.zomboidforge.api.storage.Row;
import org.jetbrains.annotations.Nullable;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.UndeclaredThrowableException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
/**
* The schema version and migrations that a storage record declares with {@link Schema} and
* {@link Migrate}. Migration methods are called through method handles from a private lookup,
* as {@link RecordCodec} reads records.
*
* @param version from {@link Schema}, or 1 without it
* @param migrations stored schema version to migration, from the {@link Migrate} methods
*/
record RecordSchema<R extends Record>(int version, Map<Integer, Function<Row, R>> migrations)
{
RecordSchema
{
migrations = Map.copyOf(migrations);
}
/** @throws IllegalArgumentException listing every invalid annotation of {@code type} */
static <R extends Record> RecordSchema<R> of(Class<R> type)
{
Schema schema = type.getAnnotation(Schema.class);
int version = schema == null ? 1 : schema.version();
List<String> problems = new ArrayList<>();
if (version < 1) problems.add("'" + type.getName() + "': @Schema(version = " + version + ") is not a version; versions start at 1.");
Method[] methods;
// Reading the methods loads every parameter and return type they name.
try { methods = type.getDeclaredMethods(); }
catch (LinkageError e) { throw new IllegalArgumentException("Cannot read the methods of '" + type.getName() + "': " + e + ".", e); }
Arrays.sort(methods, Comparator.comparing(Method::getName));
Map<Integer, Function<Row, R>> migrations = new HashMap<>();
for (Method method : methods)
{
Migrate migrate = method.getAnnotation(Migrate.class);
if (migrate == null) continue;
Function<Row, R> migration = RecordSchema.migration(type, method, migrate, migrations, problems);
if (migration != null) migrations.put(migrate.from(), migration);
}
if (!problems.isEmpty()) throw new IllegalArgumentException(String.join(" ", problems));
return new RecordSchema<>(version, migrations);
}
/** The migration of {@code method}, or {@code null} after adding its problems to {@code problems}. */
private static <R extends Record> @Nullable Function<Row, R> migration(Class<R> type, Method method, Migrate migrate, Map<Integer, Function<Row, R>> found, List<String> problems)
{
String where = "'" + type.getName() + "." + method.getName() + "'";
int before = problems.size();
if (!Modifier.isStatic(method.getModifiers())) problems.add(where + " must be static.");
if (method.getParameterCount() != 1 || method.getParameterTypes()[0] != Row.class) problems.add(where + " must have one parameter, a Row.");
if (method.getReturnType() != type) problems.add(where + " must return '" + type.getSimpleName() + "'.");
if (migrate.from() < 1) problems.add(where + ": @Migrate(from = " + migrate.from() + ") is not a version; versions start at 1.");
else if (found.containsKey(migrate.from())) problems.add(where + ": another @Migrate method migrates from version " + migrate.from() + ".");
if (problems.size() > before) return null;
try
{
MethodHandle handle = MethodHandles.privateLookupIn(type, MethodHandles.lookup()).unreflect(method);
return row -> {
// Checked exceptions are wrapped: the caller reports RuntimeExceptions of a migration with the row.
try { return type.cast(handle.invoke(row)); }
catch (RuntimeException | Error e) { throw e; }
catch (Throwable t) { throw new UndeclaredThrowableException(t, t.toString()); }
};
}
catch (IllegalAccessException e)
{
problems.add(where + " cannot be accessed: " + e.getMessage());
return null;
}
}
}
@@ -1,6 +1,9 @@
package dev.overlord.zomboidforge.core.storage;
import dev.overlord.zomboidforge.api.annotations.Migrate;
import dev.overlord.zomboidforge.api.annotations.Schema;
import dev.overlord.zomboidforge.api.storage.ModStorage;
import dev.overlord.zomboidforge.api.storage.Row;
import dev.overlord.zomboidforge.api.storage.StorageException;
import dev.overlord.zomboidforge.api.storage.Table;
import dev.overlord.zomboidforge.core.RecordingLogger;
@@ -11,6 +14,7 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
@@ -53,6 +57,43 @@ class ModTablesTest
private record RenamedDifficulty(RenamedMode mode) {}
@Schema(version = 2)
private record AnnotatedLevel(long coins, int level)
{
@Migrate(from = 1)
private static AnnotatedLevel fromV1(Row row) { return new AnnotatedLevel(row.getLong("coins") * 10, 1); }
}
@Schema(version = 2)
private record FailingMigration(long coins, int level)
{
@Migrate(from = 1)
static FailingMigration fromV1(Row row) throws IOException { throw new IOException("broken"); }
}
@Schema(version = 0)
@SuppressWarnings("unused")
private record InvalidSchema(long coins)
{
@Migrate(from = 0)
static InvalidSchema zero(Row row) { return new InvalidSchema(0); }
@Migrate(from = 1)
InvalidSchema notStatic(Row row) { return this; }
@Migrate(from = 2)
static InvalidSchema twoParameters(Row row, Row other) { return new InvalidSchema(0); }
@Migrate(from = 3)
static String wrongReturn(Row row) { return ""; }
@Migrate(from = 4)
static InvalidSchema first(Row row) { return new InvalidSchema(0); }
@Migrate(from = 4)
static InvalidSchema second(Row row) { return new InvalidSchema(0); }
}
@TempDir
Path directory;
@@ -277,6 +318,63 @@ class ModTablesTest
assertEquals(Optional.of(new Balance(1)), this.storage("shop").table("balances", Balance.class).get("a"));
}
@Test
void migratesWithTheRecordsAnnotationsAlone()
{
this.storage("shop").table("balances", Balance.class).setAll(Map.of("a", new Balance(1), "b", new Balance(2)));
Table<AnnotatedLevel> migrated = this.storage("shop").table("balances", AnnotatedLevel.class);
assertEquals(Map.of("a", new AnnotatedLevel(10, 1), "b", new AnnotatedLevel(20, 1)), migrated.getAll(List.of("a", "b")));
ModTablesTest.assertContainsAll(this.logger.messages.getLast(), "'balances'", "2 row(s)");
}
@Test
void builderCallsOverrideTheVersionAndKeepTheAnnotatedMigrations()
{
this.storage("shop").table("balances", Balance.class).set("a", new Balance(1));
Table<AnnotatedLevel> migrated = this.storage("shop").define("balances", AnnotatedLevel.class).version(3).open();
assertEquals(Optional.of(new AnnotatedLevel(10, 1)), migrated.get("a"));
StorageException older = assertThrows(StorageException.class, () -> this.storage("shop").table("balances", AnnotatedLevel.class));
ModTablesTest.assertContainsAll(older.getMessage(), "'balances'", "3", "2");
}
@Test
void allowsOneMigrationPerVersion()
{
IllegalArgumentException annotated = assertThrows(IllegalArgumentException.class, () -> this.storage("shop").define("balances", AnnotatedLevel.class)
.migrate(1, row -> new AnnotatedLevel(0, 0)));
ModTablesTest.assertContainsAll(annotated.getMessage(), AnnotatedLevel.class.getName(), "1");
IllegalArgumentException twice = assertThrows(IllegalArgumentException.class, () -> this.storage("shop").define("balances", BalanceWithLevel.class)
.migrate(1, row -> new BalanceWithLevel(0, 0))
.migrate(1, row -> new BalanceWithLevel(1, 1)));
ModTablesTest.assertContainsAll(twice.getMessage(), BalanceWithLevel.class.getName(), "1");
}
@Test
void rejectsInvalidSchemaAnnotationsWithEveryProblem()
{
IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> this.storage("shop").define("invalid", InvalidSchema.class));
ModTablesTest.assertContainsAll(e.getMessage(), "@Schema", "zero", "notStatic", "twoParameters", "wrongReturn", "second");
assertFalse(e.getMessage().contains(".first'"), "the first migration from 4 is valid: " + e.getMessage());
assertFalse(Files.exists(this.file), "nothing is stored");
}
@Test
void reportsCheckedExceptionsOfAnnotatedMigrationsWithTheRow()
{
this.storage("shop").table("balances", Balance.class).set("a", new Balance(1));
StorageException e = assertThrows(StorageException.class, () -> this.storage("shop").table("balances", FailingMigration.class));
ModTablesTest.assertContainsAll(e.getMessage(), "'a'", "java.io.IOException: broken");
assertEquals(Optional.of(new Balance(1)), this.storage("shop").table("balances", Balance.class).get("a"));
}
@Test
void adoptsTheTablesOfPreviousIdsOnce()
{
@@ -391,4 +489,9 @@ class ModTablesTest
this.database.close();
assertThrows(StorageException.class, () -> empty.contains("a"));
}
private static void assertContainsAll(String message, String... parts)
{
for (String part : parts) assertTrue(message.contains(part), "'" + part + "' missing in: " + message);
}
}