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;
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.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.BatchMoveCommand;
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.RaidModeCommand;
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.filemanager.ConfigManager;
import me.savvy.rixa.data.filemanager.LanguageManager;
import me.savvy.rixa.events.BotEvent;
import me.savvy.rixa.events.MemberEvent;
import me.savvy.rixa.events.MessageEvent;
import me.savvy.rixa.events.*;
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.ReactionManager;
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.exceptions.RateLimitedException;
import net.dv8tion.jda.core.hooks.AnnotatedEventManager;
import net.dv8tion.jda.core.requests.Route;
import javax.security.auth.login.LoginException;
import java.io.File;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
@ -69,7 +59,7 @@ public class Rixa {
private static ConfigManager config;
@Getter
@Setter
private static Database database;
private static SQLBuilder database;
@Getter
@Setter
private LanguageManager languageManager;
@ -95,16 +85,21 @@ public class Rixa {
private static void load() {
getInstance().setExecutorService(Executors.newSingleThreadScheduledExecutor());
database = Database.options()
.type("mysql")
.hostname(String.valueOf(config.getJsonObject().getJSONObject("sql").getString("hostName")), config.getJsonObject().getJSONObject("sql").getInt("portNumber"))
.database(String.valueOf(config.getJsonObject().getJSONObject("sql").getString("databaseName")))
.auth(String.valueOf(config.getJsonObject().getJSONObject("sql").getString("userName")), String.valueOf(config.getJsonObject().getJSONObject("sql").getString("password")))
.build();
database = new SQLBuilder(
config.getJsonObject().getJSONObject("sql").getString("userName"),
config.getJsonObject().getJSONObject("sql").getString("password"),
config.getJsonObject().getJSONObject("sql").getString("portNumber"),
config.getJsonObject().getJSONObject("sql").getString("databaseName"),
config.getJsonObject().getJSONObject("sql").getString("hostName"));
Arrays.stream(DatabaseTables.values()).forEach(databaseTables -> {
getInstance().getLogger().info("Checking database table (creating if needed): " + databaseTables.toString());
database.send(new Update(databaseTables.getQuery()));
try {
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")));
@ -125,7 +120,7 @@ public class Rixa {
.setStatus(OnlineStatus.ONLINE)
.setAudioEnabled(true)
.useSharding(i, shards);
shardsList.add(jda.buildBlocking());
shardsList.add(jda.buildAsync());
getInstance().getLogger().info("Shard #" + i + " has been loaded");
Thread.sleep(5000);
}
@ -163,8 +158,7 @@ public class Rixa {
public void close() {
try {
Thread.sleep(5000);
database.close();
database.closeConnection();
Thread.sleep(200);
getShardsList().forEach(JDA::shutdown);
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";
ResultSet rs = null;
try {
rs = Rixa.getDatabase().getConnection().get().prepareStatement(query).executeQuery();
rs = Rixa.getDatabase().getPreparedStatement(query).executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}

View File

@ -34,7 +34,7 @@ public class CheckGuildCommand implements CommandExec {
if (member.getUser().getId().equalsIgnoreCase(event.getAuthor().getId())) continue;
try {
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(2, member.getUser().getName());
ps.setString(3, member.getUser().getAvatarId());
@ -51,7 +51,7 @@ public class CheckGuildCommand implements CommandExec {
private boolean checkExists(String userId) {
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);
ResultSet rs = ps.executeQuery();
return rs.next();

View File

@ -15,7 +15,7 @@ public class GuildEvent {
@SubscribeEvent
public void onNameUpdate(GuildUpdateNameEvent event) {
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(2, event.getGuild().getId());
ps.executeUpdate();
@ -27,7 +27,7 @@ public class GuildEvent {
@SubscribeEvent
public void onIconUpdate(GuildUpdateIconEvent event) {
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(2, event.getGuild().getId());
ps.executeUpdate();
@ -39,7 +39,7 @@ public class GuildEvent {
@SubscribeEvent
public void onOwnerUpdate(GuildUpdateOwnerEvent event) {
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(2, event.getGuild().getId());
ps.executeUpdate();
@ -51,7 +51,7 @@ public class GuildEvent {
@SubscribeEvent
public void onRegionUpdate(GuildUpdateRegionEvent event) {
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(2, event.getGuild().getId());
ps.executeUpdate();

View File

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

View File

@ -2,11 +2,9 @@ package me.savvy.rixa.guild;
import lombok.Getter;
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.commands.handlers.RixaPermission;
import me.savvy.rixa.data.database.sql.SQLBuilder;
import me.savvy.rixa.enums.Result;
import me.savvy.rixa.guild.management.GuildSettings;
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.User;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;
/**
* Created by Timber on 5/23/2017.
@ -34,7 +32,7 @@ public class RixaGuild {
@Getter
private Guild guild;
private Database db;
private SQLBuilder db;
@Setter
private GuildSettings guildSettings;
@Getter
@ -54,10 +52,12 @@ public class RixaGuild {
public void load() {
if (!(checkExists())) {
Update update = new Update("INSERT INTO `core` (`guild_id`, `guild_name`, `description`, `keywords`) VALUES (?, ?, 'Description not set.', 'No Keywords Found.')");
update.setString(guild.getId());
update.setString(guild.getName());
db.send(update);
try {
PreparedStatement ps = db.getPreparedStatement("INSERT INTO `core` (`guild_id`, `guild_name`, `description`, `keywords`) VALUES (?, ?, 'Description not set.', 'No Keywords Found.')\"");
ps.setString(1, guild.getId());
ps.setString(2, guild.getName());
db.executeUpdate(ps);
} catch (SQLException ignored) {}
}
setGuildSettings(new GuildSettings(this.guild));
Guilds.addGuild(this);
@ -69,21 +69,10 @@ public class RixaGuild {
private boolean checkExists() {
Result r = Result.ERROR;
try {
Query query = new Query("SELECT `guild_name` FROM `core` WHERE `guild_id` = ?;");
query.setString(guild.getId());
Optional<?> optional = db.send(query);
if (!optional.isPresent()) {
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:75");
return false;
}
Rixa.getInstance().getLogger().severe("Could not find " + guild.getName() + ", GuildSettings:75");
return false;
}
ResultSet set = (ResultSet) optional.get();
PreparedStatement ps = db.getPreparedStatement("SELECT `guild_name` FROM `core` WHERE `guild_id` = ?;");
ps.setString(1, guild.getId());
ResultSet set = ps.executeQuery();
if (set.next()) {
r = Result.TRUE;
} else {
@ -116,13 +105,13 @@ public class RixaGuild {
boolean b = false;
try {
Query query = new Query("SELECT `" + permission.toString().toUpperCase() + "` FROM `permissions` WHERE `role_id` = ?");
query.setString(role.getId());
Optional<?> optional = db.send(query);
if (!optional.isPresent()) return b;
if (!(optional.get() instanceof ResultSet)) return b;
ResultSet set = (ResultSet) optional.get();
PreparedStatement ps = db.getPreparedStatement("SELECT ? FROM `permissions` WHERE `role_id` = ?");
ps.setString(1, permission.toString().toUpperCase());
ps.setString(2, role.getId());
ResultSet set = ps.executeQuery();
if (set.next()) {
b = set.getBoolean(permission.toString().toUpperCase());
}
set.close();
} catch (SQLException e) {
e.printStackTrace();
@ -132,41 +121,46 @@ public class RixaGuild {
public void setPermission(Role role, RixaPermission permission, boolean value) {
if (!permissionExists(role)) {
Update update = new Update("INSERT INTO `permissions` " +
PreparedStatement ps = null;
try {
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');");
update.setString(role.getId());
update.setString(guild.getId());
db.send(update);
ps.setString(1, role.getId());
ps.setString(2, guild.getId());
db.executeUpdate(ps);
} catch (SQLException e) {
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();
}
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 {
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();
} catch (SQLException e) {
e.printStackTrace();
}
return b;
} catch (SQLException ex) {
ex.printStackTrace();
}
return false;
}
public boolean isUserMuted(User user) {

View File

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

View File

@ -18,6 +18,7 @@ public class Guilds {
}
public static RixaGuild getGuild(Guild guild) {
if (guild == null) return null;
if (!check(guild)) {
addGuild(new RixaGuild(guild));
}
@ -29,7 +30,8 @@ public class Guilds {
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());
}
}

View File

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

View File

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

View File

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

View File

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