Add support for @Schema and @Migrate annotations to declare storage record schema versions and migrations.
This commit is contained in:
1 parent
1664bb6f28
commit
b10504e9af
8 files changed
+326
-10
No files matched your search
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user