|
| 1 | +package com.javadiscord.javabot.data.commands; |
| 2 | + |
| 3 | +import com.javadiscord.javabot.Bot; |
| 4 | +import com.javadiscord.javabot.commands.SlashCommandHandler; |
| 5 | +import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; |
| 6 | +import net.dv8tion.jda.api.requests.restaction.interactions.ReplyAction; |
| 7 | + |
| 8 | +import java.io.IOException; |
| 9 | +import java.nio.file.Files; |
| 10 | +import java.nio.file.Path; |
| 11 | +import java.sql.SQLException; |
| 12 | + |
| 13 | +/** |
| 14 | + * This subcommand exports the database schema to a file, and uploads that file |
| 15 | + * to the channel in which the command was received. |
| 16 | + */ |
| 17 | +public class ExportSchemaSubcommand implements SlashCommandHandler { |
| 18 | + private static final Path SCHEMA_FILE = Path.of("___schema.sql"); |
| 19 | + |
| 20 | + @Override |
| 21 | + public ReplyAction handle(SlashCommandEvent event) { |
| 22 | + var includeDataOption = event.getOption("include-data"); |
| 23 | + boolean includeData = includeDataOption != null && includeDataOption.getAsBoolean(); |
| 24 | + Bot.asyncPool.submit(() -> { |
| 25 | + try { |
| 26 | + var con = Bot.dataSource.getConnection(); |
| 27 | + var stmt = con.createStatement(); |
| 28 | + boolean success = stmt.execute(String.format("SCRIPT %s TO '%s';", includeData ? "" : "NODATA", SCHEMA_FILE)); |
| 29 | + if (!success) { |
| 30 | + event.getHook().sendMessage("Exporting the schema was not successful.").queue(); |
| 31 | + } else { |
| 32 | + event.getHook().sendMessage("The export was successful.").queue(); |
| 33 | + event.getChannel().sendFile(Files.newInputStream(SCHEMA_FILE), "schema.sql").complete(); |
| 34 | + Files.delete(SCHEMA_FILE); |
| 35 | + } |
| 36 | + } catch (SQLException | IOException e) { |
| 37 | + e.printStackTrace(); |
| 38 | + event.getHook().sendMessage("An error occurred, and the export could not be made: " + e.getMessage()).queue(); |
| 39 | + } |
| 40 | + }); |
| 41 | + return event.deferReply(true); |
| 42 | + } |
| 43 | +} |
0 commit comments