Add SQLite migration

This commit is contained in:
William committed 2022-08-29 13:07:34 +01:00
1 parent 70ed11fc65
commit dcc4fe68ff
5 files changed
+156 -10

No files matched your search

@@ -5,6 +5,8 @@ import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.util.BukkitUpgradeUtil;
import org.jetbrains.annotations.NotNull;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.logging.Level;
@@ -70,8 +72,24 @@ public class LegacyMigrator extends Migrator {
}
private void migrateSqLiteDatabase() {
plugin.getLoggingAdapter().log(Level.INFO, "Migrating SQLite database...");
//todo write script
plugin.getLoggingAdapter().log(Level.INFO, "Migrating SQLite database, please wait... This may take a while!");
// Execute the migration script
plugin.getDatabase().runScript(Objects.requireNonNull(plugin.getResource("migrator/sqlite_migrator.sql")),
Map.of("%target_positions_table%", plugin.getSettings().getTableName(Settings.TableName.POSITION_DATA),
"%source_positions_table%", sourceLocationsDataTable,
"%target_users_table%", plugin.getSettings().getTableName(Settings.TableName.PLAYER_DATA),
"%source_users_table%", sourcePlayerDataTable,
"%target_saved_positions%", plugin.getSettings().getTableName(Settings.TableName.SAVED_POSITION_DATA),
"%source_homes_table%", sourceHomesDataTable,
"%target_homes_table%", plugin.getSettings().getTableName(Settings.TableName.HOME_DATA),
"%source_warps_table%", sourceWarpsDataTable,
"%target_warps_table%", plugin.getSettings().getTableName(Settings.TableName.WARP_DATA)))
.thenRun(() -> plugin.getLoggingAdapter().log(Level.INFO, "Migration complete!"))
.exceptionally(e -> {
plugin.getLoggingAdapter().log(Level.SEVERE, "Migration of SQLite database failed!", e);
return null;
});
}
private void migrateMySqlDatabase() {
@@ -11,10 +11,12 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@@ -167,6 +169,15 @@ public abstract class Database {
*/
public abstract boolean initialize();
/**
* Execute a MySQL script file read as an InputStream
*
* @param inputStream The input stream to read the script from
* @return A future returning void when complete
*/
public abstract CompletableFuture<Void> runScript(@NotNull InputStream inputStream,
@NotNull Map<String, String> replacements);
/**
* <b>(Internal use only)</b> - Sets a position to the position table in the database
*
@@ -13,11 +13,10 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.logging.Level;
@@ -100,6 +99,27 @@ public class MySqlDatabase extends Database {
return false;
}
@Override
public CompletableFuture<Void> runScript(@NotNull InputStream inputStream, @NotNull Map<String, String> replacements) {
return CompletableFuture.runAsync(() -> {
try (Connection connection = getConnection()) {
final String[] scriptString;
scriptString = new String[]{new String(inputStream.readAllBytes(), StandardCharsets.UTF_8)};
replacements.forEach((key, value) -> scriptString[0] = scriptString[0].replaceAll(key, value));
connection.setAutoCommit(false);
try (Statement statement = connection.createStatement()) {
for (String statementString : scriptString[0].split(";")) {
statement.addBatch(statementString);
}
statement.executeBatch();
}
} catch (IOException | SQLException e) {
getLogger().log(Level.SEVERE, "An error occurred running a script on the MySQL database: ", e);
throw new RuntimeException(e);
}
});
}
@Override
protected int setPosition(@NotNull Position position, @NotNull Connection connection) throws SQLException {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
@@ -14,11 +14,10 @@ import org.sqlite.SQLiteConfig;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.logging.Level;
@@ -110,6 +109,31 @@ public class SqLiteDatabase extends Database {
return false;
}
@Override
public CompletableFuture<Void> runScript(@NotNull InputStream inputStream, @NotNull Map<String, String> replacements) {
return CompletableFuture.runAsync(() -> {
try {
final String[] scriptString;
scriptString = new String[]{new String(inputStream.readAllBytes(), StandardCharsets.UTF_8)};
replacements.forEach((key, value) -> scriptString[0] = scriptString[0].replaceAll(key, value));
final boolean autoCommit = getConnection().getAutoCommit();
// Execute batched SQLite script
getConnection().setAutoCommit(false);
try (Statement statement = getConnection().createStatement()) {
for (String statementString : scriptString[0].split(";")) {
statement.addBatch(statementString);
}
statement.executeBatch();
}
getConnection().setAutoCommit(autoCommit);
} catch (IOException | SQLException e) {
getLogger().log(Level.SEVERE, "An exception occurred running script on the SQLite database", e);
throw new RuntimeException(e);
}
});
}
@Override
protected int setPosition(@NotNull Position position, @NotNull Connection connection) throws SQLException {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
@@ -0,0 +1,73 @@
/* SQLite migration script. */
-- Migrate positions to the new schema
INSERT INTO `%target_positions_table%` (`id`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`)
SELECT `location_id` AS `id`,
`x`,
`y`,
`z`,
`yaw`,
`pitch`,
`world` AS `world_name`,
'00000000-0000-0000-0000-000000000000' AS `world_uuid`,
`server` AS `server_name`
FROM `%source_positions_table%`;
-- Migrate users to the new schema
INSERT INTO `%target_users_table%` (`uuid`, `username`, `last_position`, `offline_position`, `home_slots`,
`ignoring_requests`)
SELECT `user_uuid` AS `uuid`,
`username`,
`last_location_id` AS `last_position`,
`offline_location_id` AS `offline_position`,
`home_slots`,
`is_ignoring_requests` AS `ignoring_requests`
FROM `%source_users_table%`;
-- Migrate homes to the new schema
INSERT INTO `%target_saved_positions%` (`position_id`, `name`, `description`, `timestamp`)
SELECT `location_id` AS `position_id`,
`name`,
`description`,
`creation_time` AS `timestamp`
FROM `%source_homes_table%`;
INSERT INTO `%target_homes_table%` (`uuid`, `saved_position_id`, `owner_uuid`, `public`)
SELECT lower(hex(randomblob(4)) || '-' || hex(randomblob(2)) || '-' || '4' ||
substr(hex(randomblob(2)), 2) || '-' ||
substr('AB89', 1 + (abs(random()) % 4), 1) ||
substr(hex(randomblob(2)), 2) || '-' ||
hex(randomblob(6))) AS `uuid`,
`id` AS `saved_position_id`,
`user_uuid` AS `owner_uuid`,
`public`
FROM `%source_homes_table%`
INNER JOIN `%target_saved_positions%`
ON `%source_homes_table%`.`location_id` = `%target_saved_positions%`.`position_id`
INNER JOIN `%source_users_table%`
ON `%source_homes_table%`.`player_id` = `%source_users_table%`.`player_id`;
-- Migrate warps to the new schema
INSERT INTO `%target_saved_positions%` (`position_id`, `name`, `description`, `timestamp`)
SELECT `location_id` AS `position_id`,
`name`,
`description`,
`creation_time` AS `timestamp`
FROM `%source_warps_table%`;
INSERT INTO `%target_warps_table%` (`uuid`, `saved_position_id`)
SELECT lower(hex(randomblob(4)) || '-' || hex(randomblob(2)) || '-' || '4' ||
substr(hex(randomblob(2)), 2) || '-' ||
substr('AB89', 1 + (abs(random()) % 4), 1) ||
substr(hex(randomblob(2)), 2) || '-' ||
hex(randomblob(6))) AS `uuid`,
`id` AS `saved_position_id`
FROM `%source_warps_table%`
INNER JOIN `%target_saved_positions%`
ON `%source_warps_table%`.`location_id` = `%target_saved_positions%`.`position_id`;
-- Rename old tables
ALTER TABLE `%source_positions_table%` RENAME TO `old_%source_positions_table%`;
ALTER TABLE `%source_users_table%` RENAME TO `old_%source_users_table%`;
ALTER TABLE `%source_homes_table%` RENAME TO `old_%source_homes_table%`;
ALTER TABLE `%source_warps_table%` RENAME TO `old_%source_warps_table%`;