Switched to SQLBuilder, Fixed outstanding bugs

This commit is contained in:
Savvy 2017-09-30 17:45:02 -04:00
parent c2b013b4f5
commit bf746fd5ae
18 changed files with 262 additions and 767 deletions

View File

@ -1,327 +0,0 @@
package me.majrly.database;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import me.majrly.database.params.Parameter;
import me.majrly.database.statements.Query;
import me.majrly.database.statements.Statement;
import me.savvy.rixa.Rixa;
import java.sql.*;
import java.util.Map;
import java.util.Optional;
/**
* Database API
*
* @author Majrly
* @since 1.0.0
*/
public class Database {
// Variables
private String name;
private String hostname;
private String username;
private String password;
private String database;
private int port = 3306;
private HikariDataSource source;
private HikariConfig config = new HikariConfig();
/**
* Database API
*
* @param name The name of this database instance
* @param hostname The ip to use when connecting
* @param username The username to authenticate as
* @param password The password to authenticate yourself
* @param database The name of the database to switch to
* @param port The port to use when connecting
* @since 1.0.0
*/
public Database(String name, String hostname, String username, String password, String database, int port, HikariConfig config) {
this.config = config;
this.config.setJdbcUrl("jdbc:" + (this.name = name) + "://" + (this.hostname = hostname) + ":" + (this.port = port) + "/" + (this.database = database));
this.config.setDriverClassName("com.mysql.jdbc.Driver");
this.config.setUsername(this.username = username);
this.config.setPassword(this.password = password);
this.source = new HikariDataSource(config);
this.source.setPoolName("rixa");
this.source.setMaximumPoolSize(400);
}
/**
* Get the database options class
*
* @return A reference to {@link DatabaseOptions}
* @since 1.0.0
*/
public static DatabaseOptions options() {
return new DatabaseOptions();
}
/**
* Sends a query to the database
*
* @param statement The statement to send the database
* @return Either the int of an update, or the ResultSet of a query
* @since 1.0.0
*/
public Optional<?> send(Statement statement) {
Optional<PreparedStatement> optional = prepare(statement);
if (!optional.isPresent()) return Optional.empty();
PreparedStatement preparedStatement = optional.get();
try {
if (statement instanceof Query) {
return Optional.of(preparedStatement.executeQuery());
} else {
return Optional.of(preparedStatement.executeUpdate());
}
} catch (SQLException exception) {
System.out.println("INFO: Couldn't send update / query! : " + exception.getLocalizedMessage());
exception.printStackTrace();
return Optional.empty();
}
}
/**
* Close a prepared statement
*
* @param preparedStatement The prepared statement you wish to close
* @since 1.0.0
*/
public void closeStatement(PreparedStatement preparedStatement) {
try {
if (preparedStatement != null && !preparedStatement.isClosed()) {
preparedStatement.close();
}
} catch (SQLException e) {
// Can't handle closing statement
System.out.println("INFO: Close connection! : " + e.getLocalizedMessage());
e.printStackTrace();
}
}
/**
* Prepare a statement
*
* @param statement The statement with parameters you wish to prepare
* @return The optional value of {@link PreparedStatement}
* @since 1.0.0
*/
public Optional<PreparedStatement> prepare(Statement statement) {
try {
Optional<Connection> optional = getConnection();
if (!optional.isPresent()) {
Rixa.getInstance().getLogger().severe("Could not find connection, GuildSettings:117");
return Optional.empty();
}
PreparedStatement preparedStatement = optional.get().prepareStatement(statement.getSQL());
for (Map.Entry<Integer, Parameter> parameter : statement.getParameters().entrySet()) {
switch (parameter.getValue().getType()) {
case STRING:
preparedStatement.setString(parameter.getKey(), (String) parameter.getValue().getData());
break;
case INTEGER:
preparedStatement.setInt(parameter.getKey(), (Integer) parameter.getValue().getData());
break;
case DOUBLE:
preparedStatement.setDouble(parameter.getKey(), (Double) parameter.getValue().getData());
break;
case LONG:
preparedStatement.setLong(parameter.getKey(), (Long) parameter.getValue().getData());
break;
case BLOB:
preparedStatement.setBlob(parameter.getKey(), (Blob) parameter.getValue().getData());
break;
case FLOAT:
preparedStatement.setFloat(parameter.getKey(), (Float) parameter.getValue().getData());
break;
case BOOLEAN:
preparedStatement.setBoolean(parameter.getKey(), (Boolean) parameter.getValue().getData());
break;
case DATE:
preparedStatement.setDate(parameter.getKey(), (Date) parameter.getValue().getData());
break;
case OBJECT:
preparedStatement.setObject(parameter.getKey(), parameter.getValue().getData());
break;
default:
preparedStatement.setObject(parameter.getKey(), parameter.getValue().getData());
break;
}
}
return Optional.of(preparedStatement);
} catch (SQLException exception) {
System.out.println("INFO: Couldn't prepare statement : " + exception.getLocalizedMessage());
exception.printStackTrace();
return Optional.empty();
}
}
/**
* Prepare a statement
*
* @param sql The statement you want to prepare
* @return The optional value of {@link PreparedStatement}
* @since 1.0.0
*/
public Optional<PreparedStatement> prepare(String sql) {
try {
return Optional.of(source.getConnection().prepareStatement(sql));
} catch (SQLException exception) {
System.out.println("INFO: Couldn't send prepared statement! : " + exception.getLocalizedMessage());
exception.printStackTrace();
return Optional.empty();
}
}
/**
* Get the connection of MySQL
*
* @return The optional value of {@link Connection}
* @since 1.0.0
*/
public Optional<Connection> getConnection() {
try {
return Optional.of(source.getConnection());
} catch (SQLException e) {
System.out.println("INFO: Couldn't get connection : " + e.getLocalizedMessage());
return Optional.empty();
}
}
/**
* Closes the database
*
* @since 1.0.0
*/
public void close() {
source.close();
}
public String getName() {
return name;
}
public HikariConfig getConfig() {
return config;
}
public HikariDataSource getSource() {
return source;
}
/**
* Database options used for {@link Database}
*
* @author Majrly
* @since 1.0.0
*/
public static class DatabaseOptions {
// Variables
private HikariConfig config = new HikariConfig();
private String name;
private String hostname = "127.0.0.1";
private String username = "root";
private String password;
private String database;
private int port = 3306;
private int timeout = 60 * 1000;
/**
* Set a key/value in the HikariConfig
*
* @param key The key you want to set a value to
* @param value The value you want to set
* @since 1.0.0
*/
public DatabaseOptions set(String key, String value) {
config.addDataSourceProperty(key, value);
return this;
}
/**
* Set the hostname / port to connect
*
* @param hostname The hostname of the database
* @param port The port of the database
* @return This object
* @since 1.0.0
*/
public DatabaseOptions hostname(String hostname, int port) {
this.database = database;
this.port = port;
return this;
}
/**
* Set the authentication username and password
*
* @param username The user you want to authenticate as
* @param password The password you want to authenticate with
* @return This object
* @since 1.0.0
*/
public DatabaseOptions auth(String username, String password) {
this.username = username;
this.password = password;
return this;
}
/**
* Set the database to switch to
*
* @param database The database you want to switch to
* @return This object
* @since 1.0.0
*/
public DatabaseOptions database(String database) {
this.database = database;
return this;
}
/**
* Set the name of the database connection
*
* @param name The name of the database connection
* @return This object
* @since 1.0.0
*/
public DatabaseOptions type(String name) {
this.name = name;
return this;
}
/**
* Set the timeout of the connection
*
* @param timeout The max amount of time to connect
* @return This object
* @since 1.0.0
*/
public DatabaseOptions timeout(int timeout) {
this.timeout = timeout;
return this;
}
/**
* Build this class
*
* @return The database object
* @since 1.0.0
*/
public Database build() {
if (username.isEmpty()) {
username = "root";
}
return new Database(name, hostname, username, password, database, port, config);
}
}
}

View File

@ -1,54 +0,0 @@
package me.majrly.database.params;
/**
* Apart of the Database API to set parameters (AKA those little question marks in sql statements)
*
* @author Majrly
* @since 1.0.0
*/
public class Parameter {
// Variables
private Object data;
private Type type = Type.OBJECT;
/**
* Used to set parameters
*
* @param type The type of data you want sent
* @param data The data
* @since 1.0.0
*/
public Parameter(Type type, Object data) {
this.type = type;
this.data = data;
}
/**
* Used to set parameters
*
* @param data The object data
* @since 1.0.0
*/
public Parameter(Object data) {
this.data = data;
}
/**
* The type of data you want sent
*
* @author Majrly
* @since 1.0.0
*/
public enum Type {
STRING, BLOB, INTEGER, DOUBLE, FLOAT, DATE, LONG, BOOLEAN, OBJECT;
}
public Object getData() {
return data;
}
public Type getType() {
return type;
}
}

View File

@ -1,14 +0,0 @@
package me.majrly.database.statements;
/**
* Apart of the Database API to differentiate between various Statements
*
* @author Majrly
* @since 1.0.0
*/
public class Query extends Statement {
public Query(String sql) {
super(sql);
}
}

View File

@ -1,120 +0,0 @@
package me.majrly.database.statements;
import me.majrly.database.params.Parameter;
import java.sql.Blob;
import java.sql.Date;
import java.util.HashMap;
/**
* Apart of the Database API to create MySQL statements
*
* @author Majrly
* @since 1.0.0
*/
public class Statement {
// Variables
private String sql;
private int amount = 1;
private HashMap<Integer, Parameter> parameters = new HashMap<Integer, Parameter>();
/**
* Used to create SQL statements
*
* @param sql The SQL string
* @since 1.0.0
*/
public Statement(String sql) {
this.sql = sql;
}
/**
* Escape a string
*
* @param data The string you want to escape
* @since 1.0.0
*/
public void setString(String data) {
this.parameters.put(amount++, new Parameter(Parameter.Type.STRING, data));
}
/**
* Escape a string
*
* @param data The Blob you want to escape
* @since 1.0.0
*/
public void setBlob(Blob data) {
this.parameters.put(amount++, new Parameter(Parameter.Type.BLOB, data));
}
/**
* Escape a double
*
* @param data The double you want to escape
* @since 1.0.0
*/
public void setDouble(double data) {
this.parameters.put(amount++, new Parameter(Parameter.Type.DOUBLE, data));
}
/**
* Escape an integer
*
* @param data The integer you want to escape
* @since 1.0.0
*/
public void setInteger(int data) {
this.parameters.put(amount++, new Parameter(Parameter.Type.INTEGER, data));
}
/**
* Escape a float
*
* @param data The float you want to escape
* @since 1.0.0
*/
public void setFloat(float data) {
this.parameters.put(amount++, new Parameter(Parameter.Type.FLOAT, data));
}
/**
* Escape a date
*
* @param data The date you want to escape
* @since 1.0.0
*/
public void setDate(Date data) {
this.parameters.put(amount++, new Parameter(Parameter.Type.DATE, data));
}
/**
* Escape a boolean
*
* @param data The boolean you want to escape
* @since 1.0.0
*/
public void setBoolean(boolean data) {
this.parameters.put(amount++, new Parameter(Parameter.Type.BOOLEAN, data));
}
/**
* Escape an object
*
* @param data The object you want to escape
* @since 1.0.0
*/
public void setObject(Object data) {
this.parameters.put(amount++, new Parameter(Parameter.Type.OBJECT, data));
}
// Getters
public String getSQL() {
return sql;
}
public HashMap<Integer, Parameter> getParameters() {
return parameters;
}
}

View File

@ -1,14 +0,0 @@
package me.majrly.database.statements;
/**
* Apart of the Database API to differentiate between various Statements
*
* @author Majrly
* @since 1.0.0
*/
public class Update extends Statement {
public Update(String sql) {
super(sql);
}
}

View File

@ -1,13 +1,7 @@
package me.savvy.rixa; package me.savvy.rixa;
import com.google.code.chatterbotapi.ChatterBot;
import com.google.code.chatterbotapi.ChatterBotFactory;
import com.google.code.chatterbotapi.ChatterBotSession;
import com.google.code.chatterbotapi.ChatterBotType;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import me.majrly.database.Database;
import me.majrly.database.statements.Update;
import me.savvy.rixa.commands.admin.AddRoleCommand; import me.savvy.rixa.commands.admin.AddRoleCommand;
import me.savvy.rixa.commands.admin.BatchMoveCommand; import me.savvy.rixa.commands.admin.BatchMoveCommand;
import me.savvy.rixa.commands.admin.ConfigCommand; import me.savvy.rixa.commands.admin.ConfigCommand;
@ -20,16 +14,12 @@ import me.savvy.rixa.commands.mod.MuteCommand;
import me.savvy.rixa.commands.mod.PurgeMessagesCommand; import me.savvy.rixa.commands.mod.PurgeMessagesCommand;
import me.savvy.rixa.commands.mod.RaidModeCommand; import me.savvy.rixa.commands.mod.RaidModeCommand;
import me.savvy.rixa.commands.owner.OwnerCommand; import me.savvy.rixa.commands.owner.OwnerCommand;
import me.savvy.rixa.data.database.sql.SQLBuilder;
import me.savvy.rixa.data.database.sql.other.DatabaseTables; import me.savvy.rixa.data.database.sql.other.DatabaseTables;
import me.savvy.rixa.data.filemanager.ConfigManager; import me.savvy.rixa.data.filemanager.ConfigManager;
import me.savvy.rixa.data.filemanager.LanguageManager; import me.savvy.rixa.data.filemanager.LanguageManager;
import me.savvy.rixa.events.BotEvent; import me.savvy.rixa.events.*;
import me.savvy.rixa.events.MemberEvent;
import me.savvy.rixa.events.MessageEvent;
import me.savvy.rixa.events.Shutdown; import me.savvy.rixa.events.Shutdown;
import me.savvy.rixa.events.VoiceChannel;
import me.savvy.rixa.guild.RixaGuild;
import me.savvy.rixa.guild.management.Guilds;
import me.savvy.rixa.modules.reactions.handlers.React; import me.savvy.rixa.modules.reactions.handlers.React;
import me.savvy.rixa.modules.reactions.handlers.ReactionManager; import me.savvy.rixa.modules.reactions.handlers.ReactionManager;
import me.savvy.rixa.modules.reactions.react.ConfigReaction; import me.savvy.rixa.modules.reactions.react.ConfigReaction;
@ -42,10 +32,10 @@ import net.dv8tion.jda.core.OnlineStatus;
import net.dv8tion.jda.core.entities.Game; import net.dv8tion.jda.core.entities.Game;
import net.dv8tion.jda.core.exceptions.RateLimitedException; import net.dv8tion.jda.core.exceptions.RateLimitedException;
import net.dv8tion.jda.core.hooks.AnnotatedEventManager; import net.dv8tion.jda.core.hooks.AnnotatedEventManager;
import net.dv8tion.jda.core.requests.Route;
import javax.security.auth.login.LoginException; import javax.security.auth.login.LoginException;
import java.io.File; import java.io.File;
import java.sql.SQLException;
import java.util.Arrays; import java.util.Arrays;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
@ -69,7 +59,7 @@ public class Rixa {
private static ConfigManager config; private static ConfigManager config;
@Getter @Getter
@Setter @Setter
private static Database database; private static SQLBuilder database;
@Getter @Getter
@Setter @Setter
private LanguageManager languageManager; private LanguageManager languageManager;
@ -95,16 +85,21 @@ public class Rixa {
private static void load() { private static void load() {
getInstance().setExecutorService(Executors.newSingleThreadScheduledExecutor()); getInstance().setExecutorService(Executors.newSingleThreadScheduledExecutor());
database = Database.options() database = new SQLBuilder(
.type("mysql") config.getJsonObject().getJSONObject("sql").getString("userName"),
.hostname(String.valueOf(config.getJsonObject().getJSONObject("sql").getString("hostName")), config.getJsonObject().getJSONObject("sql").getInt("portNumber")) config.getJsonObject().getJSONObject("sql").getString("password"),
.database(String.valueOf(config.getJsonObject().getJSONObject("sql").getString("databaseName"))) config.getJsonObject().getJSONObject("sql").getString("portNumber"),
.auth(String.valueOf(config.getJsonObject().getJSONObject("sql").getString("userName")), String.valueOf(config.getJsonObject().getJSONObject("sql").getString("password"))) config.getJsonObject().getJSONObject("sql").getString("databaseName"),
.build(); config.getJsonObject().getJSONObject("sql").getString("hostName"));
Arrays.stream(DatabaseTables.values()).forEach(databaseTables -> { Arrays.stream(DatabaseTables.values()).forEach(databaseTables -> {
getInstance().getLogger().info("Checking database table (creating if needed): " + databaseTables.toString()); getInstance().getLogger().info("Checking database table (creating if needed): " + databaseTables.toString());
database.send(new Update(databaseTables.getQuery())); try {
getInstance().getLogger().info("Done checking " + databaseTables.toString()); database.executeUpdate(databaseTables.getQuery());
getInstance().getLogger().info("Done checking " + databaseTables.toString());
} catch (SQLException e) {
getInstance().getLogger().severe("Could not create table: " + databaseTables.toString());
e.printStackTrace();
}
}); });
getInstance().setLanguageManager(new LanguageManager(new File("Rixa/languages/language.json"))); getInstance().setLanguageManager(new LanguageManager(new File("Rixa/languages/language.json")));
@ -125,7 +120,7 @@ public class Rixa {
.setStatus(OnlineStatus.ONLINE) .setStatus(OnlineStatus.ONLINE)
.setAudioEnabled(true) .setAudioEnabled(true)
.useSharding(i, shards); .useSharding(i, shards);
shardsList.add(jda.buildBlocking()); shardsList.add(jda.buildAsync());
getInstance().getLogger().info("Shard #" + i + " has been loaded"); getInstance().getLogger().info("Shard #" + i + " has been loaded");
Thread.sleep(5000); Thread.sleep(5000);
} }
@ -163,8 +158,7 @@ public class Rixa {
public void close() { public void close() {
try { try {
Thread.sleep(5000); database.closeConnection();
database.close();
Thread.sleep(200); Thread.sleep(200);
getShardsList().forEach(JDA::shutdown); getShardsList().forEach(JDA::shutdown);
Thread.sleep(200); Thread.sleep(200);

View File

@ -53,7 +53,7 @@ public class LevelsCommand implements CommandExec {
String query = "SELECT * FROM `levels` WHERE `guild_id` = '" + rixaGuild.getGuild().getId() + "' ORDER BY `experience` DESC"; String query = "SELECT * FROM `levels` WHERE `guild_id` = '" + rixaGuild.getGuild().getId() + "' ORDER BY `experience` DESC";
ResultSet rs = null; ResultSet rs = null;
try { try {
rs = Rixa.getDatabase().getConnection().get().prepareStatement(query).executeQuery(); rs = Rixa.getDatabase().getPreparedStatement(query).executeQuery();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }

View File

@ -34,7 +34,7 @@ public class CheckGuildCommand implements CommandExec {
if (member.getUser().getId().equalsIgnoreCase(event.getAuthor().getId())) continue; if (member.getUser().getId().equalsIgnoreCase(event.getAuthor().getId())) continue;
try { try {
if (!(checkExists(member.getUser().getId()))) { if (!(checkExists(member.getUser().getId()))) {
PreparedStatement ps = Rixa.getDatabase().getConnection().get().prepareStatement("INSERT INTO `user` (`user_id`, `user_name`, `avatar_hash`) VALUES (?, ?, ?)"); PreparedStatement ps = Rixa.getDatabase().getPreparedStatement("INSERT INTO `user` (`user_id`, `user_name`, `avatar_hash`) VALUES (?, ?, ?)");
ps.setString(1, member.getUser().getId()); ps.setString(1, member.getUser().getId());
ps.setString(2, member.getUser().getName()); ps.setString(2, member.getUser().getName());
ps.setString(3, member.getUser().getAvatarId()); ps.setString(3, member.getUser().getAvatarId());
@ -51,7 +51,7 @@ public class CheckGuildCommand implements CommandExec {
private boolean checkExists(String userId) { private boolean checkExists(String userId) {
try { try {
PreparedStatement ps = Rixa.getDatabase().getConnection().get().prepareStatement("SELECT `user_id` FROM `user` WHERE `user_id` = ?;"); PreparedStatement ps = Rixa.getDatabase().getPreparedStatement("SELECT `user_id` FROM `user` WHERE `user_id` = ?;");
ps.setString(1, userId); ps.setString(1, userId);
ResultSet rs = ps.executeQuery(); ResultSet rs = ps.executeQuery();
return rs.next(); return rs.next();

View File

@ -15,7 +15,7 @@ public class GuildEvent {
@SubscribeEvent @SubscribeEvent
public void onNameUpdate(GuildUpdateNameEvent event) { public void onNameUpdate(GuildUpdateNameEvent event) {
try { try {
PreparedStatement ps = Rixa.getDatabase().getConnection().get().prepareStatement("UPDATE `core` SET `guild_name` = ? WHERE `core`.`guild_id` = ?;"); PreparedStatement ps = Rixa.getDatabase().getPreparedStatement("UPDATE `core` SET `guild_name` = ? WHERE `core`.`guild_id` = ?;");
ps.setString(1, event.getGuild().getName()); ps.setString(1, event.getGuild().getName());
ps.setString(2, event.getGuild().getId()); ps.setString(2, event.getGuild().getId());
ps.executeUpdate(); ps.executeUpdate();
@ -27,7 +27,7 @@ public class GuildEvent {
@SubscribeEvent @SubscribeEvent
public void onIconUpdate(GuildUpdateIconEvent event) { public void onIconUpdate(GuildUpdateIconEvent event) {
try { try {
PreparedStatement ps = Rixa.getDatabase().getConnection().get().prepareStatement("UPDATE `core` SET `icon` = ? WHERE `core`.`guild_id` = ?;"); PreparedStatement ps = Rixa.getDatabase().getPreparedStatement("UPDATE `core` SET `icon` = ? WHERE `core`.`guild_id` = ?;");
ps.setString(1, event.getGuild().getIconId()); ps.setString(1, event.getGuild().getIconId());
ps.setString(2, event.getGuild().getId()); ps.setString(2, event.getGuild().getId());
ps.executeUpdate(); ps.executeUpdate();
@ -39,7 +39,7 @@ public class GuildEvent {
@SubscribeEvent @SubscribeEvent
public void onOwnerUpdate(GuildUpdateOwnerEvent event) { public void onOwnerUpdate(GuildUpdateOwnerEvent event) {
try { try {
PreparedStatement ps = Rixa.getDatabase().getConnection().get().prepareStatement("UPDATE `core` SET `guild_owner` = ? WHERE `core`.`guild_id` = ?;"); PreparedStatement ps = Rixa.getDatabase().getPreparedStatement("UPDATE `core` SET `guild_owner` = ? WHERE `core`.`guild_id` = ?;");
ps.setString(1, event.getGuild().getOwner().getUser().getName()); ps.setString(1, event.getGuild().getOwner().getUser().getName());
ps.setString(2, event.getGuild().getId()); ps.setString(2, event.getGuild().getId());
ps.executeUpdate(); ps.executeUpdate();
@ -51,7 +51,7 @@ public class GuildEvent {
@SubscribeEvent @SubscribeEvent
public void onRegionUpdate(GuildUpdateRegionEvent event) { public void onRegionUpdate(GuildUpdateRegionEvent event) {
try { try {
PreparedStatement ps = Rixa.getDatabase().getConnection().get().prepareStatement("UPDATE `core` SET `guild_region` = ? WHERE `core`.`guild_id` = ?;"); PreparedStatement ps = Rixa.getDatabase().getPreparedStatement("UPDATE `core` SET `guild_region` = ? WHERE `core`.`guild_id` = ?;");
ps.setString(1, event.getGuild().getRegion().getName()); ps.setString(1, event.getGuild().getRegion().getName());
ps.setString(2, event.getGuild().getId()); ps.setString(2, event.getGuild().getId());
ps.executeUpdate(); ps.executeUpdate();

View File

@ -1,7 +1,6 @@
package me.savvy.rixa.events; package me.savvy.rixa.events;
import com.mysql.jdbc.StringUtils; import com.mysql.jdbc.StringUtils;
import me.savvy.rixa.Rixa;
import me.savvy.rixa.commands.handlers.CommandHandler; import me.savvy.rixa.commands.handlers.CommandHandler;
import me.savvy.rixa.commands.handlers.CommandRegistrar; import me.savvy.rixa.commands.handlers.CommandRegistrar;
import me.savvy.rixa.guild.RixaGuild; import me.savvy.rixa.guild.RixaGuild;
@ -90,6 +89,7 @@ public class MessageEvent {
return; return;
} }
CommandRegistrar cmd = CommandHandler.get(splitContent[0]); CommandRegistrar cmd = CommandHandler.get(splitContent[0]);
if (cmd == null) return;
Method m = cmd.getMethod(); Method m = cmd.getMethod();
try { try {
m.invoke(cmd.getExecutor(), event); m.invoke(cmd.getExecutor(), event);

View File

@ -2,11 +2,9 @@ package me.savvy.rixa.guild;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import me.majrly.database.Database;
import me.majrly.database.statements.Query;
import me.majrly.database.statements.Update;
import me.savvy.rixa.Rixa; import me.savvy.rixa.Rixa;
import me.savvy.rixa.commands.handlers.RixaPermission; import me.savvy.rixa.commands.handlers.RixaPermission;
import me.savvy.rixa.data.database.sql.SQLBuilder;
import me.savvy.rixa.enums.Result; import me.savvy.rixa.enums.Result;
import me.savvy.rixa.guild.management.GuildSettings; import me.savvy.rixa.guild.management.GuildSettings;
import me.savvy.rixa.guild.management.Guilds; import me.savvy.rixa.guild.management.Guilds;
@ -19,12 +17,12 @@ import net.dv8tion.jda.core.entities.Member;
import net.dv8tion.jda.core.entities.Role; import net.dv8tion.jda.core.entities.Role;
import net.dv8tion.jda.core.entities.User; import net.dv8tion.jda.core.entities.User;
import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Optional;
/** /**
* Created by Timber on 5/23/2017. * Created by Timber on 5/23/2017.
@ -34,7 +32,7 @@ public class RixaGuild {
@Getter @Getter
private Guild guild; private Guild guild;
private Database db; private SQLBuilder db;
@Setter @Setter
private GuildSettings guildSettings; private GuildSettings guildSettings;
@Getter @Getter
@ -54,10 +52,12 @@ public class RixaGuild {
public void load() { public void load() {
if (!(checkExists())) { if (!(checkExists())) {
Update update = new Update("INSERT INTO `core` (`guild_id`, `guild_name`, `description`, `keywords`) VALUES (?, ?, 'Description not set.', 'No Keywords Found.')"); try {
update.setString(guild.getId()); PreparedStatement ps = db.getPreparedStatement("INSERT INTO `core` (`guild_id`, `guild_name`, `description`, `keywords`) VALUES (?, ?, 'Description not set.', 'No Keywords Found.')\"");
update.setString(guild.getName()); ps.setString(1, guild.getId());
db.send(update); ps.setString(2, guild.getName());
db.executeUpdate(ps);
} catch (SQLException ignored) {}
} }
setGuildSettings(new GuildSettings(this.guild)); setGuildSettings(new GuildSettings(this.guild));
Guilds.addGuild(this); Guilds.addGuild(this);
@ -69,27 +69,16 @@ public class RixaGuild {
private boolean checkExists() { private boolean checkExists() {
Result r = Result.ERROR; Result r = Result.ERROR;
try { try {
Query query = new Query("SELECT `guild_name` FROM `core` WHERE `guild_id` = ?;"); PreparedStatement ps = db.getPreparedStatement("SELECT `guild_name` FROM `core` WHERE `guild_id` = ?;");
query.setString(guild.getId()); ps.setString(1, guild.getId());
Optional<?> optional = db.send(query); ResultSet set = ps.executeQuery();
if (set.next()) {
if (!optional.isPresent()) { r = Result.TRUE;
if (!(optional.get() instanceof ResultSet)) { } else {
Rixa.getInstance().getLogger().severe("Could not find " + guild.getName() + " in settings it wasn't an instance of result set!, GuildSettings:75"); r = Result.FALSE;
return false;
}
Rixa.getInstance().getLogger().severe("Could not find " + guild.getName() + ", GuildSettings:75");
return false;
} }
ResultSet set = (ResultSet) optional.get(); set.close();
if (set.next()) {
r = Result.TRUE;
} else {
r = Result.FALSE;
}
set.close();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -116,13 +105,13 @@ public class RixaGuild {
boolean b = false; boolean b = false;
try { try {
Query query = new Query("SELECT `" + permission.toString().toUpperCase() + "` FROM `permissions` WHERE `role_id` = ?"); PreparedStatement ps = db.getPreparedStatement("SELECT ? FROM `permissions` WHERE `role_id` = ?");
query.setString(role.getId()); ps.setString(1, permission.toString().toUpperCase());
Optional<?> optional = db.send(query); ps.setString(2, role.getId());
if (!optional.isPresent()) return b; ResultSet set = ps.executeQuery();
if (!(optional.get() instanceof ResultSet)) return b; if (set.next()) {
ResultSet set = (ResultSet) optional.get(); b = set.getBoolean(permission.toString().toUpperCase());
b = set.getBoolean(permission.toString().toUpperCase()); }
set.close(); set.close();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
@ -132,41 +121,46 @@ public class RixaGuild {
public void setPermission(Role role, RixaPermission permission, boolean value) { public void setPermission(Role role, RixaPermission permission, boolean value) {
if (!permissionExists(role)) { if (!permissionExists(role)) {
Update update = new Update("INSERT INTO `permissions` " + PreparedStatement ps = null;
"(`role_id`, `guild_id`, `MUTE`, `ADD_ROLE`, `REMOVE_ROLE`, `CLEAR_CHAT`, " +
"`ACCESS_CONFIG`, `PM_MESSAGE`, `KICK_MEMBER`, `BAN_MEMBER`)" +
" VALUES (?, ?, '0', '0', '0', '0', '0', '0', '0', '0');");
update.setString(role.getId());
update.setString(guild.getId());
db.send(update);
}
Update update = new Update("UPDATE `permissions` SET `" + permission.toString().toUpperCase() + "` = ? WHERE `guild_id` = ? AND `role_id` = ?;");
update.setBoolean(value);
update.setString(guild.getId());
update.setString(role.getId());
db.send(update);
}
private boolean permissionExists(Role role) {
Query query = new Query("SELECT `" + RixaPermission.values()[0] + "` FROM `permissions` WHERE `guild_id` = ? AND `role_id` = ?");
query.setString(guild.getId());
query.setString(role.getId());
Optional<?> optional = db.send(query);
if (!optional.isPresent()) return false;
if (!(optional.get() instanceof ResultSet)) return false;
ResultSet set = (ResultSet) optional.get();
try {
return set.next();
} catch (SQLException e) {
e.printStackTrace();
return false;
} finally {
try { try {
set.close(); ps = db.getPreparedStatement("INSERT INTO `permissions` " +
"(`role_id`, `guild_id`, `MUTE`, `ADD_ROLE`, `REMOVE_ROLE`, `CLEAR_CHAT`, " +
"`ACCESS_CONFIG`, `PM_MESSAGE`, `KICK_MEMBER`, `BAN_MEMBER`)" +
" VALUES (?, ?, '0', '0', '0', '0', '0', '0', '0', '0');");
ps.setString(1, role.getId());
ps.setString(2, guild.getId());
db.executeUpdate(ps);
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
try {
PreparedStatement ps = db.getPreparedStatement("UPDATE `permissions` SET ? = ? WHERE `guild_id` = ? AND `role_id` = ?;");
ps.setString(1, permission.toString().toUpperCase());
ps.setBoolean(2, value);
ps.setString(3, guild.getId());
ps.setString(4, role.getId());
db.executeUpdate(ps);
} catch (SQLException ex) {
ex.printStackTrace();
}
}
private boolean permissionExists(Role role) {
try {
PreparedStatement query = db.getPreparedStatement("SELECT ? FROM `permissions` WHERE `guild_id` = ? AND `role_id` = ?");
query.setString(1, RixaPermission.values()[0].toString().toUpperCase());
query.setString(2, guild.getId());
query.setString(3, role.getId());
ResultSet set = query.executeQuery();
boolean b = set.next();
query.close();
set.close();
return b;
} catch (SQLException ex) {
ex.printStackTrace();
}
return false;
} }
public boolean isUserMuted(User user) { public boolean isUserMuted(User user) {

View File

@ -2,16 +2,15 @@ package me.savvy.rixa.guild.management;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import me.majrly.database.statements.Query;
import me.majrly.database.statements.Update;
import me.savvy.rixa.Rixa; import me.savvy.rixa.Rixa;
import me.savvy.rixa.data.database.sql.SQLBuilder;
import me.savvy.rixa.enums.Result; import me.savvy.rixa.enums.Result;
import net.dv8tion.jda.core.entities.Guild; import net.dv8tion.jda.core.entities.Guild;
import net.dv8tion.jda.core.entities.TextChannel; import net.dv8tion.jda.core.entities.TextChannel;
import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.Optional;
import java.util.TimerTask; import java.util.TimerTask;
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@ -36,6 +35,7 @@ public class GuildSettings {
long lastJoin; long lastJoin;
private boolean raidMode; private boolean raidMode;
private SQLBuilder db;
public GuildSettings(Guild guild) { public GuildSettings(Guild guild) {
this.guild = guild; this.guild = guild;
try { try {
@ -46,23 +46,18 @@ public class GuildSettings {
} }
private void load() throws SQLException { private void load() throws SQLException {
db = Rixa.getDatabase();
if (!checkExists()) { if (!checkExists()) {
Update update = new Update("INSERT INTO settings(guild_id, log_enabled, log_channel, joinMessage, quitMessage, greetings, farewell, prefix, joinPm, joinVerification, defaultRole, muteRole) VALUES ('" + guild.getId() + "', '0', 'default_value', 'default_value', 'default_value', 'default_value', 'default_value', '/', 'default', '0', 'default_value', 'default_value');"); PreparedStatement statement = db.getPreparedStatement
Rixa.getDatabase().send(update); ("INSERT INTO settings(guild_id, log_enabled, log_channel, joinMessage, quitMessage, greetings, farewell, prefix, joinPm, joinVerification, defaultRole, muteRole) VALUES " +
"(?, '0', 'default_value', 'default_value', 'default_value', 'default_value', 'default_value', '/', 'default', '0', 'default_value', 'default_value');");
statement.setString(1, guild.getId());
statement.executeUpdate();
return; return;
} }
Query query = new Query("SELECT * FROM `settings` WHERE `guild_id` = ?"); PreparedStatement statement = db.getPreparedStatement("SELECT * FROM `settings` WHERE `guild_id` = ?");
query.setString(guild.getId()); statement.setString(1, guild.getId());
Optional<?> optional = Rixa.getDatabase().send(query); ResultSet set = statement.executeQuery();
if (!optional.isPresent()) {
if (!(optional.get() instanceof ResultSet)) {
Rixa.getInstance().getLogger().severe("Could not find " + guild.getName() + " it wasn't an instance of result set!, GuildSettings:61");
return;
}
Rixa.getInstance().getLogger().severe("Could not find " + guild.getName() + ", GuildSettings:60");
return;
}
ResultSet set = (ResultSet) optional.get();
if (set.next()) { if (set.next()) {
this.prefix = (set.getString("prefix")); this.prefix = (set.getString("prefix"));
this.defaultRole = (set.getString("defaultRole")); this.defaultRole = (set.getString("defaultRole"));
@ -78,12 +73,9 @@ public class GuildSettings {
quitMessageChannel = guild.getTextChannelById(set.getString("farewell")); quitMessageChannel = guild.getTextChannelById(set.getString("farewell"));
} }
} }
query = new Query("SELECT * FROM `core` WHERE `guild_id` = ?"); statement = db.getPreparedStatement("SELECT * FROM `core` WHERE `guild_id` = ?");
query.setString(guild.getId()); statement.setString(1, guild.getId());
optional = Rixa.getDatabase().send(query); set = statement.executeQuery();
if (!optional.isPresent()) return;
if (!(optional.get() instanceof ResultSet)) return;
set = (ResultSet) optional.get();
if (set.next()) { if (set.next()) {
this.description = (set.getString("description")); this.description = (set.getString("description"));
this.enlisted = (set.getBoolean("enlisted")); this.enlisted = (set.getBoolean("enlisted"));
@ -94,18 +86,10 @@ public class GuildSettings {
private boolean checkExists() { private boolean checkExists() {
Result r; Result r;
try { try {
Query query = new Query("SELECT `guild_id` FROM `settings` WHERE `guild_id` = ?"); PreparedStatement statement = db.getPreparedStatement
query.setString(guild.getId()); ("SELECT `guild_id` FROM `settings` WHERE `guild_id` = ?");
Optional<?> optional = Rixa.getDatabase().send(query); statement.setString(1, guild.getId());
if (!optional.isPresent()) { ResultSet set = statement.executeQuery();
if (!(optional.get() instanceof ResultSet)) {
Rixa.getInstance().getLogger().severe("Could not find " + guild.getName() + " in settings it wasn't an instance of result set!, GuildSettings:97");
return false;
}
Rixa.getInstance().getLogger().severe("Could not find " + guild.getName() + ", GuildSettings:99");
return false;
}
ResultSet set = (ResultSet) optional.get();
if (set.next()) { if (set.next()) {
r = Result.TRUE; r = Result.TRUE;
} else { } else {
@ -125,74 +109,130 @@ public class GuildSettings {
public void setJoinMessage(String joinMessage) { public void setJoinMessage(String joinMessage) {
this.joinMessage = joinMessage; this.joinMessage = joinMessage;
update("settings", "joinMessage", "guild_id", joinMessage, guild.getId()); try {
update("settings", "joinMessage", "guild_id", joinMessage, guild.getId());
} catch (SQLException e) {
e.printStackTrace();
}
} }
public void setQuitMessage(String quitMessage) { public void setQuitMessage(String quitMessage) {
this.quitMessage = quitMessage; this.quitMessage = quitMessage;
update("settings", "quitMessage", "guild_id", quitMessage, guild.getId()); try {
update("settings", "quitMessage", "guild_id", quitMessage, guild.getId());
} catch (SQLException e) {
e.printStackTrace();
}
} }
public void setJoinPrivateMessage(String joinPrivateMessage) { public void setJoinPrivateMessage(String joinPrivateMessage) {
this.joinPrivateMessage = joinPrivateMessage; this.joinPrivateMessage = joinPrivateMessage;
update("settings", "joinPM", "guild_id", joinPrivateMessage, guild.getId()); try {
update("settings", "joinPM", "guild_id", joinPrivateMessage, guild.getId());
} catch (SQLException e) {
e.printStackTrace();
}
} }
public void setJoinMessageChannel(TextChannel joinMessageChannel) { public void setJoinMessageChannel(TextChannel joinMessageChannel) {
this.joinMessageChannel = joinMessageChannel; this.joinMessageChannel = joinMessageChannel;
update("settings", "greetings", "guild_id", joinMessageChannel.getId(), guild.getId()); try {
update("settings", "greetings", "guild_id", joinMessageChannel.getId(), guild.getId());
} catch (SQLException e) {
e.printStackTrace();
}
} }
public void setJoinMessageChannel(String joinMessageChannel) { public void setJoinMessageChannel(String joinMessageChannel) {
if (joinMessageChannel.equalsIgnoreCase("default_value")) this.joinMessageChannel = null; if (joinMessageChannel.equalsIgnoreCase("default_value")) this.joinMessageChannel = null;
update("settings", "greetings", "guild_id", joinMessageChannel, guild.getId()); try {
update("settings", "greetings", "guild_id", joinMessageChannel, guild.getId());
} catch (SQLException e) {
e.printStackTrace();
}
} }
private void update(String table, String setting, String key, Object placeholder, Object placeholder2) { private void update(String table, String setting, String key, Object placeholder, Object placeholder2) throws SQLException {
Update update = new Update("UPDATE `" + table + "` SET `" + setting + "` = ? WHERE `" + key + "` = ?;"); PreparedStatement statement = db.getPreparedStatement("UPDATE ? SET ? = ? WHERE ? = ?;");
update.setObject(placeholder); statement.setString(1, table);
update.setObject(placeholder2); statement.setString(2, setting);
Rixa.getDatabase().send(update); statement.setObject(3, placeholder);
statement.setString(4, key);
statement.setObject(5, placeholder2);
statement.executeUpdate();
statement.close();
} }
public void setQuitMessageChannel(TextChannel quitMessageChannel) { public void setQuitMessageChannel(TextChannel quitMessageChannel) {
this.quitMessageChannel = quitMessageChannel; this.quitMessageChannel = quitMessageChannel;
update("settings", "farewell", "guild_id", quitMessageChannel.getId(), guild.getId()); try {
update("settings", "farewell", "guild_id", quitMessageChannel.getId(), guild.getId());
} catch (SQLException e) {
e.printStackTrace();
}
} }
public void setQuitMessageChannel(String quitMessageChannel) { public void setQuitMessageChannel(String quitMessageChannel) {
if (quitMessageChannel.equalsIgnoreCase("default_value")) this.quitMessageChannel = null; if (quitMessageChannel.equalsIgnoreCase("default_value")) this.quitMessageChannel = null;
update("settings", "greetings", "guild_id", quitMessageChannel, guild.getId()); try {
update("settings", "greetings", "guild_id", quitMessageChannel, guild.getId());
} catch (SQLException e) {
e.printStackTrace();
}
} }
public void setDefaultRole(String defaultRole) { public void setDefaultRole(String defaultRole) {
this.defaultRole = defaultRole; this.defaultRole = defaultRole;
update("settings", "defaultRole", "guild_id", defaultRole, guild.getId()); try {
update("settings", "defaultRole", "guild_id", defaultRole, guild.getId());
} catch (SQLException e) {
e.printStackTrace();
}
} }
public void setPrefix(String prefix) { public void setPrefix(String prefix) {
this.prefix = prefix; this.prefix = prefix;
update("settings", "prefix", "guild_id", prefix, guild.getId()); try {
update("settings", "prefix", "guild_id", prefix, guild.getId());
} catch (SQLException e) {
e.printStackTrace();
}
} }
public void setDescription(String description) { public void setDescription(String description) {
this.description = description; this.description = description;
update("core", "description", "guild_id", description, guild.getId()); try {
update("core", "description", "guild_id", description, guild.getId());
} catch (SQLException e) {
e.printStackTrace();
}
} }
public void setEnlisted(boolean enlisted) { public void setEnlisted(boolean enlisted) {
this.enlisted = enlisted; this.enlisted = enlisted;
update("core", "enlisted", "guild_id", enlisted, guild.getId()); try {
update("core", "enlisted", "guild_id", enlisted, guild.getId());
} catch (SQLException e) {
e.printStackTrace();
}
} }
public void setMuteRole(String muteRole) { public void setMuteRole(String muteRole) {
this.muteRole = muteRole; this.muteRole = muteRole;
update("settings", "muteRole", "guild_id", muteRole, guild.getId()); try {
update("settings", "muteRole", "guild_id", muteRole, guild.getId());
} catch (SQLException e) {
e.printStackTrace();
}
} }
public void setJoinVerification(boolean joinVerification) { public void setJoinVerification(boolean joinVerification) {
this.joinVerification = joinVerification; this.joinVerification = joinVerification;
update("settings", "joinVerification", "guild_id", joinVerification, guild.getId()); try {
update("settings", "joinVerification", "guild_id", joinVerification, guild.getId());
} catch (SQLException e) {
e.printStackTrace();
}
} }
public void startRaidMode() { public void startRaidMode() {

View File

@ -18,6 +18,7 @@ public class Guilds {
} }
public static RixaGuild getGuild(Guild guild) { public static RixaGuild getGuild(Guild guild) {
if (guild == null) return null;
if (!check(guild)) { if (!check(guild)) {
addGuild(new RixaGuild(guild)); addGuild(new RixaGuild(guild));
} }
@ -29,7 +30,8 @@ public class Guilds {
guilds.remove(guild.getGuild().getId()); guilds.remove(guild.getGuild().getId());
} }
public static boolean check(Guild guild) { private static boolean check(Guild guild) {
if (guild == null) return false;
return guilds.containsKey(guild.getId()); return guilds.containsKey(guild.getId());
} }
} }

View File

@ -1,8 +1,6 @@
package me.savvy.rixa.guild.user; package me.savvy.rixa.guild.user;
import lombok.Getter; import lombok.Getter;
import me.majrly.database.statements.Query;
import me.majrly.database.statements.Update;
import me.savvy.rixa.Rixa; import me.savvy.rixa.Rixa;
import me.savvy.rixa.enums.Result; import me.savvy.rixa.enums.Result;
import me.savvy.rixa.guild.management.Guilds; import me.savvy.rixa.guild.management.Guilds;
@ -10,9 +8,9 @@ import me.savvy.rixa.modules.levels.LevelsModule;
import net.dv8tion.jda.core.entities.Guild; import net.dv8tion.jda.core.entities.Guild;
import net.dv8tion.jda.core.entities.User; import net.dv8tion.jda.core.entities.User;
import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.Optional;
import java.util.Random; import java.util.Random;
import java.util.Timer; import java.util.Timer;
import java.util.TimerTask; import java.util.TimerTask;
@ -50,13 +48,10 @@ public class UserData {
return; return;
} }
try { try {
Query query = new Query("SELECT * FROM `levels` WHERE `guild_id` = ? AND `user_id` = ?;"); PreparedStatement statement = Rixa.getDatabase().getPreparedStatement("SELECT * FROM `levels` WHERE `guild_id` = ? AND `user_id` = ?;");
query.setString(guild.getId()); statement.setString(1, guild.getId());
query.setString(user.getId()); statement.setString(2, user.getId());
Optional<?> optional = Rixa.getDatabase().send(query); ResultSet set = statement.executeQuery();
if (!optional.isPresent()) return;
if (!(optional.get() instanceof ResultSet)) return;
ResultSet set = (ResultSet) optional.get();
if (set.next()) { if (set.next()) {
setExperience(set.getInt("experience")); setExperience(set.getInt("experience"));
} }
@ -111,21 +106,16 @@ public class UserData {
} }
private boolean checkExists() { private boolean checkExists() {
Result r = Result.FALSE; Result r;
try { try {
Query query = new Query("SELECT `user_id` FROM `levels` WHERE `guild_id` = ? AND `user_id` = ?;"); PreparedStatement statement = Rixa.getDatabase().getPreparedStatement("SELECT `user_id` FROM `levels` WHERE `guild_id` = ? AND `user_id` = ?;");
query.setString(guild.getId()); statement.setString(1, guild.getId());
query.setString(user.getId()); statement.setString(2, user.getId());
Optional<?> optional = Rixa.getDatabase().send(query); ResultSet set = statement.executeQuery();
if (!optional.isPresent()) r = Result.ERROR; if (set.next()) {
if (!(optional.get() instanceof ResultSet)) r = Result.ERROR; r = Result.TRUE;
ResultSet set = (ResultSet) optional.get(); } else {
if (r != Result.ERROR) { r = Result.FALSE;
if (set.next()) {
r = Result.TRUE;
} else {
r = Result.FALSE;
}
} }
set.close(); set.close();
return r == Result.TRUE; return r == Result.TRUE;
@ -136,21 +126,29 @@ public class UserData {
} }
private void insert() { private void insert() {
Update update = new Update("INSERT INTO `levels` (guild_id, user_id, experience) VALUES (?, ?, ?);"); try {
update.setString(guild.getId()); PreparedStatement statement = Rixa.getDatabase().getPreparedStatement("INSERT INTO `levels` (guild_id, user_id, experience) VALUES (?, ?, ?);");
update.setString(user.getId()); statement.setString(1, guild.getId());
update.setInteger(0); statement.setString(2, user.getId());
Rixa.getDatabase().send(update); statement.setInt(3, 0);
statement.executeUpdate();
} catch (SQLException ex) {
ex.printStackTrace();
}
} }
private void setExperience(int experience) { private void setExperience(int experience) {
this.experience = experience; this.experience = experience;
String query = "UPDATE `levels` SET `experience` = ? WHERE `guild_id` = ? AND `user_id` = ?;"; String query = "UPDATE `levels` SET `experience` = ? WHERE `guild_id` = ? AND `user_id` = ?;";
Update update = new Update(query); try {
update.setInteger(experience); PreparedStatement ps = Rixa.getDatabase().getPreparedStatement(query);
update.setString(guild.getId()); ps.setInt(1, experience);
update.setString(user.getId()); ps.setString(2, guild.getId());
Rixa.getDatabase().send(update); ps.setString(3, user.getId());
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
} }
private int getRandom() { private int getRandom() {

View File

@ -2,10 +2,8 @@ package me.savvy.rixa.modules.levels;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import me.majrly.database.Database;
import me.majrly.database.statements.Query;
import me.majrly.database.statements.Update;
import me.savvy.rixa.Rixa; import me.savvy.rixa.Rixa;
import me.savvy.rixa.data.database.sql.SQLBuilder;
import me.savvy.rixa.guild.RixaGuild; import me.savvy.rixa.guild.RixaGuild;
import me.savvy.rixa.guild.user.UserData; import me.savvy.rixa.guild.user.UserData;
import me.savvy.rixa.modules.RixaModule; import me.savvy.rixa.modules.RixaModule;
@ -16,7 +14,10 @@ import net.dv8tion.jda.core.entities.Member;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.*; import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/** /**
* Created by Timber on 5/23/2017. * Created by Timber on 5/23/2017.
@ -30,6 +31,7 @@ public class LevelsModule implements RixaModule {
@Getter @Getter
@Setter @Setter
private boolean enabled; private boolean enabled;
private SQLBuilder db;
public LevelsModule(RixaGuild rixaGuild) { public LevelsModule(RixaGuild rixaGuild) {
this.rixaGuild = rixaGuild; this.rixaGuild = rixaGuild;
@ -38,19 +40,17 @@ public class LevelsModule implements RixaModule {
@Override @Override
public void load() { public void load() {
this.db = Rixa.getDatabase();
try { try {
Query query = new Query("SELECT * FROM `modules` WHERE `guild_id`=?;"); PreparedStatement query = db.getPreparedStatement("SELECT * FROM `modules` WHERE `guild_id`= ?;");
query.setString(rixaGuild.getGuild().getId()); query.setString(1, rixaGuild.getGuild().getId());
Optional<?> o = Rixa.getDatabase().send(query); ResultSet set = query.executeQuery();
if (!o.isPresent()) return;
else if (!(o.get() instanceof ResultSet)) return;
ResultSet set = (ResultSet) o.get();
if (set.next()) { if (set.next()) {
setEnabled(set.getBoolean("levels")); setEnabled(set.getBoolean("levels"));
} else { } else {
Update update = new Update("INSERT INTO `modules` (`guild_id`) VALUES (?);"); query = db.getPreparedStatement("INSERT INTO `modules` (`guild_id`) VALUES (?);");
update.setString(rixaGuild.getGuild().getId()); query.setString(1, rixaGuild.getGuild().getId());
Rixa.getDatabase().send(update); query.executeUpdate();
setEnabled(true); setEnabled(true);
} }
set.close(); set.close();
@ -60,11 +60,10 @@ public class LevelsModule implements RixaModule {
} }
private List<UserData> leaderboard(Member member) { private List<UserData> leaderboard(Member member) {
Database db = Rixa.getDatabase();
ResultSet rs = null; ResultSet rs = null;
PreparedStatement ps = null;
try { try {
PreparedStatement ps = db.getConnection().get().prepareStatement("SELECT * FROM `levels` WHERE `guild_id` = ? ORDER BY `experience` DESC;"); ps = db.getPreparedStatement("SELECT * FROM `levels` WHERE `guild_id` = ? ORDER BY `experience` DESC;");
ps.setString(1, member.getGuild().getId()); ps.setString(1, member.getGuild().getId());
rs = ps.executeQuery(); rs = ps.executeQuery();
} catch (SQLException e) { } catch (SQLException e) {
@ -78,7 +77,7 @@ public class LevelsModule implements RixaModule {
UserData userData = ((LevelsModule) rixaGuild.getModule("Levels")).getUserData(rs.getString("user_id")); UserData userData = ((LevelsModule) rixaGuild.getModule("Levels")).getUserData(rs.getString("user_id"));
userDataList.add(userData); userDataList.add(userData);
} }
rs.getStatement().close(); ps.close();
rs.close(); rs.close();
} catch (SQLException ex) { } catch (SQLException ex) {
ex.printStackTrace(); ex.printStackTrace();

View File

@ -2,24 +2,22 @@ package me.savvy.rixa.modules.music;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import me.majrly.database.Database;
import me.majrly.database.statements.Query;
import me.majrly.database.statements.Update;
import me.savvy.rixa.Rixa; import me.savvy.rixa.Rixa;
import me.savvy.rixa.data.database.sql.SQLBuilder;
import me.savvy.rixa.guild.RixaGuild; import me.savvy.rixa.guild.RixaGuild;
import me.savvy.rixa.modules.RixaModule; import me.savvy.rixa.modules.RixaModule;
import me.savvy.rixa.utils.DatabaseUtils; import me.savvy.rixa.utils.DatabaseUtils;
import net.dv8tion.jda.core.entities.Guild; import net.dv8tion.jda.core.entities.Guild;
import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.Optional;
/** /**
* Created by Timber on 5/23/2017. * Created by Timber on 5/23/2017.
*/ */
public class MusicModule implements RixaModule { public class MusicModule implements RixaModule {
private Database db; private SQLBuilder db;
@Getter @Getter
@Setter @Setter
private boolean enabled; private boolean enabled;
@ -41,15 +39,13 @@ public class MusicModule implements RixaModule {
this.musicRole = "default_value"; this.musicRole = "default_value";
db = Rixa.getDatabase(); db = Rixa.getDatabase();
if (!DatabaseUtils.checkExists("music", guild)) { if (!DatabaseUtils.checkExists("music", guild)) {
Update update = new Update("INSERT INTO `music` (`guild_id`, `music_role`, `enabled`) VALUES ('" + guild.getId() + "', 'default_value', '0');"); PreparedStatement statement = db.getPreparedStatement("INSERT INTO `music` (`guild_id`, `music_role`, `enabled`) VALUES (?, 'default_value', '0');");
db.send(update); statement.setString(1, guild.getId());
statement.executeUpdate();
} }
Query query = new Query("SELECT * FROM `music` WHERE `guild_id` = ?"); PreparedStatement statement = db.getPreparedStatement("SELECT * FROM `music` WHERE `guild_id` = ?");
query.setString(guild.getId()); statement.setString(1, guild.getId());
Optional<?> optional = Rixa.getDatabase().send(query); ResultSet set = statement.executeQuery();
if (!optional.isPresent()) return;
if (!(optional.get() instanceof ResultSet)) return;
ResultSet set = (ResultSet) optional.get();
if (set.next()) { if (set.next()) {
setMusicRole(set.getString("music_role")); setMusicRole(set.getString("music_role"));
setEnabled(set.getBoolean("enabled")); setEnabled(set.getBoolean("enabled"));

View File

@ -9,6 +9,7 @@ import me.savvy.rixa.modules.reactions.handlers.ReactHandle;
import net.dv8tion.jda.core.EmbedBuilder; import net.dv8tion.jda.core.EmbedBuilder;
import net.dv8tion.jda.core.entities.ChannelType; import net.dv8tion.jda.core.entities.ChannelType;
import net.dv8tion.jda.core.entities.Message; import net.dv8tion.jda.core.entities.Message;
import net.dv8tion.jda.core.entities.MessageEmbed;
import net.dv8tion.jda.core.events.message.react.MessageReactionAddEvent; import net.dv8tion.jda.core.events.message.react.MessageReactionAddEvent;
import net.dv8tion.jda.core.exceptions.ErrorResponseException; import net.dv8tion.jda.core.exceptions.ErrorResponseException;
@ -25,8 +26,11 @@ public class HelpReaction implements React {
return; return;
} }
Message message = event.getChannel().getMessageById(event.getMessageId()).complete(); Message message = event.getChannel().getMessageById(event.getMessageId()).complete();
String title = message.getEmbeds().get(0).getTitle().split(": ")[1]; MessageEmbed messageEmbed = message.getEmbeds().get(0);
if (!messageEmbed.getTitle().contains(": ")) return;
String title = messageEmbed.getTitle().split(": ")[1];
RixaGuild rixaGuild = Guilds.getGuild(event.getJDA().getGuildById(title)); RixaGuild rixaGuild = Guilds.getGuild(event.getJDA().getGuildById(title));
if (rixaGuild == null) return;
String prefix = rixaGuild.getGuildSettings().getPrefix(); String prefix = rixaGuild.getGuildSettings().getPrefix();
EmbedBuilder embedBuilder; EmbedBuilder embedBuilder;
try { try {

View File

@ -1,42 +1,39 @@
package me.savvy.rixa.utils; package me.savvy.rixa.utils;
import me.majrly.database.statements.Query;
import me.majrly.database.statements.Update;
import me.savvy.rixa.Rixa; import me.savvy.rixa.Rixa;
import me.savvy.rixa.enums.Result; import me.savvy.rixa.enums.Result;
import net.dv8tion.jda.core.entities.Guild; import net.dv8tion.jda.core.entities.Guild;
import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.Optional;
public class DatabaseUtils { public class DatabaseUtils {
public static Result update(String table, String setting, String key, Object placeholder, Object placeholder2) { public static Result update(String table, String setting, String key, Object placeholder, Object placeholder2) {
Update update = new Update("UPDATE `" + table + "` SET `" + setting + "` = ? WHERE `" + key + "` = ?;"); PreparedStatement statement = null;
update.setObject(placeholder); try {
update.setObject(placeholder2); statement = Rixa.getDatabase().getPreparedStatement("UPDATE `" + table + "` SET ? = ? WHERE `" + key + "` = ?;");
Rixa.getDatabase().send(update); statement.setString(1, setting);
statement.setObject(2, placeholder);
statement.setObject(3, placeholder2);
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
return Result.FALSE;
}
return Result.TRUE; return Result.TRUE;
} }
public static boolean checkExists(String table, Guild guild) { public static boolean checkExists(String table, Guild guild) {
Result r = Result.FALSE;
try { try {
Query query = new Query("SELECT `guild_id` FROM `" + table + "` WHERE `guild_id` = '" + guild.getId() + "';"); PreparedStatement statement = Rixa.getDatabase().getPreparedStatement("SELECT `guild_id` FROM `" + table + "` WHERE `guild_id` = ?;");
Optional<?> optional = Rixa.getDatabase().send(query); statement.setString(1, guild.getId());
if (!optional.isPresent()) r = Result.ERROR; ResultSet set = statement.executeQuery();
if (!(optional.get() instanceof ResultSet)) r = Result.ERROR; boolean b = set.next();
ResultSet set = (ResultSet) optional.get(); statement.close();
if (r != Result.ERROR) {
if (set.next()) {
r = Result.TRUE;
} else {
r = Result.FALSE;
}
}
set.close(); set.close();
return r == Result.TRUE; return b;
} catch (SQLException e) { } catch (SQLException e) {
System.out.println("INFO: Failed to check if exists : " + e.getLocalizedMessage()); System.out.println("INFO: Failed to check if exists : " + e.getLocalizedMessage());
return false; return false;