From 57ffb95027efa842c8d946caeebac8c0a78a8504 Mon Sep 17 00:00:00 2001 From: mathias Date: Thu, 24 Dec 2020 10:26:30 +0100 Subject: [PATCH] version 1.0 --- src/README.md | 130 ++++++++++ src/main/java/drivers/MySQLConnection.java | 253 +++++++++++++++++++ src/main/java/drivers/SqlLogManager.java | 92 +++++++ src/main/java/fields/SQLField.java | 110 ++++++++ src/main/java/generator/TableGenerator.java | 84 ++++++ src/main/java/manager/DataBaseSelection.java | 160 ++++++++++++ src/main/java/manager/ResultManager.java | 117 +++++++++ src/main/java/manager/UpdateManager.java | 206 +++++++++++++++ src/main/java/types/LogLevelType.java | 20 ++ src/main/java/types/LoginParam.java | 37 +++ src/main/java/types/SQLType.java | 28 ++ 11 files changed, 1237 insertions(+) create mode 100644 src/README.md create mode 100755 src/main/java/drivers/MySQLConnection.java create mode 100755 src/main/java/drivers/SqlLogManager.java create mode 100644 src/main/java/fields/SQLField.java create mode 100644 src/main/java/generator/TableGenerator.java create mode 100644 src/main/java/manager/DataBaseSelection.java create mode 100644 src/main/java/manager/ResultManager.java create mode 100644 src/main/java/manager/UpdateManager.java create mode 100644 src/main/java/types/LogLevelType.java create mode 100644 src/main/java/types/LoginParam.java create mode 100644 src/main/java/types/SQLType.java diff --git a/src/README.md b/src/README.md new file mode 100644 index 0000000..c6efc50 --- /dev/null +++ b/src/README.md @@ -0,0 +1,130 @@ +[![Contributors][contributors-shield]][contributors-url] +[![Forks][forks-shield]][forks-url] +[![Stargazers][stars-shield]][stars-url] +[![Issues][issues-shield]][issues-url] +[![MIT License][license-shield]][license-url] + + + +
+

+ + Logo + +

+

MySQL Toolkit

+ +## About The Project +This is a small project for quickly managing a MySQL database in Java. It makes everyday life with a database much easier. + +### Installation +1. Clone the repo + ```sh + git clone https://github.com/germannewsmaker/sqltoolkit.git + ``` +2. Move the project into a package of your project (in most cases "sql") +3. Ready! Have fun +#### Maven comming soon + +### Usage Examples +1. Create a connection + - Example of a constructor without optional specifications + ```java + MySQLConnection connection = new MySQLConnection(hostname, username, password, database).connect(); + ``` + - Example of a constructor with setting the logging level + ```java + MySQLConnection connection = new MySQLConnection(hostname, username, password, database, LogLevelType.ALL).connect(); + ``` + - Example of a constructor with optional login parameters + ```java + MySQLConnection connection = new MySQLConnection(hostname, username, password, database, LoginParam.AUTO_RECONNECT, LoginParam.NO_SSL).connect(); + ``` + #### Logging Levels + - NONE - Sends nothing + - LOW - Sends Warnings & Errors + - ALL - Sends Infos, Warnings & Errors + #### Login Parameters + - DEFAULT *(useSSL=false&autoReconnect=true&useUnicode=yes&characterEncoding=UTF-8&useTimezone=true&serverTimezone=UTC)* + - NO_SSL *(useSSL=false)* + - USE_SSL *(useSSL=true)* + - AUTO_RECONNECT *(autoReconnect=true)* + - UTF8_ENCODING *(characterEncoding=UTF-8)* + - USE_UNICODE *(useUnicode=yes)* + - USE_TIMEZONE *(useTimezone=true)* + - TIMEZONE_UTC *(serverTimezone=UTC)* +2. Perform a standard SQL query + - Get a ResultSet + ```java + connection.getResultSet("default query", "parameters"); + ``` + - Perform an update + ```java + connection.update("query", "parameters"); + ``` +3. Get something from a table with managers + 1. Getting a Result (For one result) + ```java + String value = connection.getResult("query", "parameters") + .getString("column"); + ``` + 2. Getting Results (For more than one) + ```java + ArrayList list = connection.getResult("query", "parameters") + .getList("column"); + ``` + 3. Choosing Results + ```java + connection + .selectFrom("table") + .where("column", "value") + .limit(10) + .getResult(); + ``` + 4. Choosing Results + Print the current statement + ```java + connection.select() + .from("table") + .where("column", "value") + .add("LIMIT 2,5") + .printStatement(); + ``` +4. Perform an update using managers + 1. Update a Table + ```java + connection + .update() + .toTable("table") + .where("column", "value") + .set("column", "newValue") + .update(); + ``` + 2. Generate a Table + ```java + connection + .update() + .generateTable("table") + .useID() + .addField(new SQLField(SQLType.STRING, "column", 999)) + .addField(new SQLField(SQLType.STRING, "column2", 25)) + .create(); + ``` + + +## License + +Distributed under the MIT License. See `LICENSE` for more information. + +## End +Currently there are not many features yet, so feel free to write me some suggestions! + +[contributors-shield]: https://img.shields.io/github/contributors/germannewsmaker/sqltoolkit.svg?style=for-the-badge +[contributors-url]: https://github.com/germannewsmaker/sqltoolkit/graphs/contributors +[forks-shield]: https://img.shields.io/github/forks/germannewsmaker/sqltoolkit.svg?style=for-the-badge +[forks-url]: https://github.com/germannewsmaker/sqltoolkit/network/members +[stars-shield]: https://img.shields.io/github/stars/germannewsmaker/sqltoolkit.svg?style=for-the-badge +[stars-url]: https://github.com/germannewsmaker/sqltoolkit/stargazers +[issues-shield]: https://img.shields.io/github/issues/germannewsmaker/sqltoolkit.svg?style=for-the-badge +[issues-url]: https://github.com/germannewsmaker/sqltoolkit/issues +[license-shield]: https://img.shields.io/github/license/germannewsmaker/sqltoolkit.svg?style=for-the-badge +[license-url]: https://github.com/germannewsmaker/sqltoolkit/blob/master/LICENSE.txt \ No newline at end of file diff --git a/src/main/java/drivers/MySQLConnection.java b/src/main/java/drivers/MySQLConnection.java new file mode 100755 index 0000000..b097338 --- /dev/null +++ b/src/main/java/drivers/MySQLConnection.java @@ -0,0 +1,253 @@ +package drivers; + +import manager.ResultManager; +import manager.DataBaseSelection; +import manager.UpdateManager; +import types.LogLevelType; +import types.LoginParam; + +import java.sql.*; + +/******************************** + * @author Mathias Wagner + * Created 23.12.2020 + ********************************/ + +public class MySQLConnection { + + private final String hostname; + private final String username; + private final String password; + private final String database; + private String tablePrefix = ""; + private String tablePrefixVariable = ""; + private String connectString = ""; + public static Connection con; + private final SqlLogManager sqlLogManager; + + /** + * Update the Connection String + * @param loginParams New login parameters + * @return this class + */ + public MySQLConnection updateConnectString(LoginParam... loginParams) { + this.connectString = getConnectionString(loginParams); + return this; + } + + /** + * Set the Connection String + * @param tablePrefixVariable New table prefix variable + * @return this class + */ + public MySQLConnection setTablePrefixVariable(String tablePrefixVariable) { + this.tablePrefixVariable = tablePrefixVariable; + return this; + } + + /** + * Set the current table Prefix + * @param tablePrefix New table prefix + * @return this class + */ + public MySQLConnection setTablePrefix(String tablePrefix) { + this.tablePrefix = tablePrefix; + return this; + } + + /** + * Get the current table Prefix + * @return the prefix + */ + public String getTablePrefix() { + return tablePrefix; + } + + /** + * Get the current jdbc connection string for mysql + * @param loginParams login parameters + * @return the string + */ + private String getConnectionString(LoginParam[] loginParams) { + boolean used = false;StringBuilder currentString = new StringBuilder(); + for (LoginParam param : loginParams) { + String currentChar = (used) ? "&" : "?";used = true; + currentString.append(currentChar).append(param.getValue()); + } + return currentString.toString(); + } + + /** + * Check if you are connected + * @return status of the connection + */ + public boolean isConnected() { + return (con != null); + } + + /** + * Get the SQL Log Manager and adjust it how you like it + * @return the SQL Log Manager + */ + public SqlLogManager getLogManager() { + return sqlLogManager; + } + + /** + * Basic constructor for the Connection + * @param hostname MySQL server hostname + * @param username MySQL server username + * @param password MySQL server password + * @param database MySQL server database + * @param logLevel Logging level + * @param loginParams Login parameters + */ + public MySQLConnection(String hostname, String username, String password, String database, LogLevelType logLevel, LoginParam... loginParams) { + this.hostname = hostname; + this.username = username; + this.password = password; + this.database = database; + this.sqlLogManager = new SqlLogManager(); + updateConnectString(loginParams); + setLogLevelType(logLevel); + } + + /** + * Basic constructor for the Connection + * @param hostname MySQL server hostname + * @param username MySQL server username + * @param password MySQL server password + * @param database MySQL server database + * @param loginParams Login parameters + */ + public MySQLConnection(String hostname, String username, String password, String database, LoginParam... loginParams) { + this.hostname = hostname; + this.username = username; + this.password = password; + this.database = database; + this.sqlLogManager = new SqlLogManager(); + updateConnectString(loginParams); + setLogLevelType(LogLevelType.NONE); + } + + /** + * Set a new logging level + * @param logLevelType New logging level + * @return this class + */ + public MySQLConnection setLogLevelType(LogLevelType logLevelType) { + this.sqlLogManager.setLogLevelType(logLevelType); + return this; + } + + /** + * Get a result from your server + * @param query Search query + * @param params Optional parameters + * @return ResultSet + */ + public ResultSet getResultSet(String query, Object... params) { + query = (tablePrefix.isEmpty()) ? "" : query.replace((tablePrefixVariable.isEmpty()) ? "$tp" : tablePrefixVariable, tablePrefix); + try { int start = 1; + PreparedStatement ps = con.prepareStatement(query); + for (Object current : params) { ps.setObject(start, current);start++; } + return ps.executeQuery(); + } catch (Exception err) { + sqlLogManager.sendError(err.getMessage()); + } + return null; + } + + /** + * Get a result from your server (get the Manager) + * @param query Search query + * @param params Optional parameters + * @return ResultManager + */ + public ResultManager getResult(String query, Object... params) { + return new ResultManager(getResultSet(query, params), sqlLogManager); + } + + /** + * Update something on your server by query + * @param query Update query + * @param params Optional parameters + * @return this class + */ + public MySQLConnection update(String query, Object... params) { + query = (tablePrefix.isEmpty()) ? "" : query.replace((tablePrefixVariable.isEmpty()) ? "$tp" : tablePrefixVariable, tablePrefix); + try { int start = 1; + PreparedStatement ps = con.prepareStatement(query); + for (Object current : params) { ps.setObject(start, current);start++; } + ps.executeUpdate(); + } catch (Exception err) { err.printStackTrace(); } + return this; + } + + /** + * Get the update manager for easier updating + * @return Update manager + */ + public UpdateManager update() { + return new UpdateManager(this); + } + + /** + * Get the update manager for easier updating (pre filled table) + * @param tableName The name of the table + * @return Update manager + */ + public UpdateManager updateTable(String tableName) { + return new UpdateManager(this, tableName); + } + + /** + * Get the Database Selection for easier selection of tables (pre filled table) + * @param tableName The name of the table + * @return DatabaseSelection + */ + public DataBaseSelection selectFrom(String tableName) { + return new DataBaseSelection(this, tableName); + } + + /** + * Get the Database Selection for easier selection of tables + * @return DatabaseSelection + */ + public DataBaseSelection select() { + return new DataBaseSelection(this); + } + + /** + * Connect with your MySQL server + * @return this class + */ + public MySQLConnection connect() { + if (!isConnected()) { try { + sqlLogManager.sendInfo("Connecting to " + hostname + " with user " + username + " to database " + database); + Class.forName("com.mysql.cj.jdbc.Driver"); + con = DriverManager.getConnection("jdbc:mysql://" + hostname + "/" + database + connectString, username, password); + sqlLogManager.sendInfo("Connection established"); + } catch (Exception exception) { + if (exception.getMessage().equals("jdbc.Driver")) + sqlLogManager.sendError("MySQL driver not found! Check your dependencies or install the JDBC Mysql Driver from https://dev.mysql.com/downloads/file/?id=498587"); + else if (exception.getMessage().contains("has not received any packets")) sqlLogManager.sendError("No packets received from the server."); + else if (exception.getMessage().contains("denied for user")) sqlLogManager.sendError("Wrong username/password"); + else sqlLogManager.sendError(exception.getMessage()); + } + } else sqlLogManager.sendWarning("Already connected"); + return this; + } + + /** + * Disconnect from your MySQL Server + * @return this class + */ + public MySQLConnection disconnect() { + if (isConnected()) { try { con.close();con = null;sqlLogManager.sendInfo("Connection closed"); + } catch (Exception err) { sqlLogManager.sendError(err.getMessage()); } + } else sqlLogManager.sendWarning("Not connected. Please connect first"); + return this; + } + +} diff --git a/src/main/java/drivers/SqlLogManager.java b/src/main/java/drivers/SqlLogManager.java new file mode 100755 index 0000000..0d777df --- /dev/null +++ b/src/main/java/drivers/SqlLogManager.java @@ -0,0 +1,92 @@ +package drivers; + +import types.LogLevelType; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; + +/******************************** + * @author Mathias Wagner + * Created 23.12.2020 + ********************************/ + +public class SqlLogManager { + + private LogLevelType logLevelType; + private String logFormat = "[%date » MySQL %type] %msg"; + + /** + * Sets the Log Level + * @param logLevelType Logging Level + */ + public void setLogLevelType(LogLevelType logLevelType) { + this.logLevelType = logLevelType; + } + + /** + * Format for the Message + * @param logFormat The Formatted String + */ + public void setLogFormat(String logFormat) { + this.logFormat = logFormat; + } + + /** + * Getting the Logging Level + * @return LogLevelType + */ + public LogLevelType getLogLevelType() { + return logLevelType; + } + + /** + * Send an information + * @param msg The provided message + */ + public void sendInfo(String msg) { + if (logLevelType == LogLevelType.ALL) + sendLog("Info", msg); + } + + /** + * Send an Warning + * @param msg The provided message + */ + public void sendWarning(String msg) { + if (logLevelType == LogLevelType.ALL || logLevelType == LogLevelType.LOW) + sendLog("Warning", msg); + } + + /** + * Send an Error + * @param msg The provided message + */ + public void sendError(String msg) { + if (logLevelType == LogLevelType.ALL || logLevelType == LogLevelType.LOW) { + StackTraceElement[] st = Thread.currentThread().getStackTrace(); + StackTraceElement stack = st[st.length-1]; + sendLog("Error", "<"+stack.getFileName()+":"+stack.getLineNumber()+"> "+msg); + } + } + + /** + * Intern Logging Feature + * @param prefix Logging Prefix + * @param msg The provided message + */ + private void sendLog(String prefix, String msg) { + String formatted = logFormat.replace("%type", prefix).replace("%date", getDate()).replace("%msg", msg); + System.out.println(formatted); + } + + /** + * Getting the date + * @return Datetime + */ + private String getDate() { + DateTimeFormatter dtf = DateTimeFormatter.ofPattern("H:m:s"); + LocalDateTime dt = LocalDateTime.now(); + return dtf.format(dt); + } + +} diff --git a/src/main/java/fields/SQLField.java b/src/main/java/fields/SQLField.java new file mode 100644 index 0000000..cffed27 --- /dev/null +++ b/src/main/java/fields/SQLField.java @@ -0,0 +1,110 @@ +package fields; + +import types.SQLType; + +/******************************** + * @author Mathias Wagner + * Created 23.12.2020 + ********************************/ + +public class SQLField { + + private String name = ""; + private String defaultValue = ""; + private String optionalParameter = ""; + private Integer length = 0; + private SQLType sqlType; + + /** + * Basic constructor for the SQL field + * @param sqlType Type of the SQL field + * @param name Name of the SQL field + * @param length Length of the SQL field + */ + public SQLField(SQLType sqlType, String name, Integer length) { + this.name = name; + this.sqlType = sqlType; + this.length = length; + } + + /** + * Set the default value for the SQL field + * @param defaultValue New default value + * @return this class + */ + public SQLField setDefaultValue(String defaultValue) { + this.defaultValue = defaultValue; + return this; + } + + /** + * Set optional parameter for the SQL field + * @param optionalParameter New optional parameter + * @return this class + */ + public SQLField setOptionalParameter(String optionalParameter) { + this.optionalParameter = optionalParameter; + return this; + } + + /** + * Set the length of the SQL field + * @param length New length + * @return this class + */ + public SQLField setLength(Integer length) { + this.length = length; + return this; + } + + /** + * Set the name of the SQL field + * @param name New name + * @return this class + */ + public SQLField setName(String name) { + this.name = name; + return this; + } + + /** + * Get the length of the SQL Field + * @return length + */ + public Integer getLength() { + return length; + } + + /** + * Get the default value of the SQL Field + * @return default value + */ + public String getDefaultValue() { + return defaultValue; + } + + /** + * Get the optional parameters of the SQL Field + * @return this class + */ + public String getOptionalParameter() { + return optionalParameter; + } + + /** + * Get the name of the SQL Field + * @return name + */ + public String getName() { + return name; + } + + /** + * Get the SQL Type of the SQL Field + * @return SQL Type + */ + public SQLType getSqlType() { + return sqlType; + } + +} diff --git a/src/main/java/generator/TableGenerator.java b/src/main/java/generator/TableGenerator.java new file mode 100644 index 0000000..027dfb0 --- /dev/null +++ b/src/main/java/generator/TableGenerator.java @@ -0,0 +1,84 @@ +package generator; + +import drivers.MySQLConnection; +import fields.SQLField; +import manager.UpdateManager; + +import java.util.ArrayList; +import java.util.concurrent.atomic.AtomicBoolean; + +/******************************** + * @author Mathias Wagner + * Created 23.12.2020 + ********************************/ + +public class TableGenerator { + + private UpdateManager updateManager; + private ArrayList fields; + private boolean useID; + private String tableName; + MySQLConnection connection; + + /** + * Basic constructor for the TableGenerator + * @param updateManager Existing update manager + * @param tableName Name of the table + */ + public TableGenerator(UpdateManager updateManager, String tableName) { + this.updateManager = updateManager; + this.tableName = tableName; + this.fields = new ArrayList<>(); + connection = updateManager.getConnection(); + } + + /** + * Add an 'id' field to the Table + * @return this class + */ + public TableGenerator useID() { + this.useID = true; + return this; + } + + /** + * Add a field to the Table + * @param field String of the field + * @return this class + */ + public TableGenerator addField(String field) { + fields.add(field); + return this; + } + + /** + * Add a field to the Table + * @param field Existing SQL Field + * @return this class + */ + public TableGenerator addField(SQLField field) { + String temp = ""; + temp += "`" + field.getName() + "` " + field.getSqlType().getValue() + "(" + field.getLength() + ")"; + temp += !field.getDefaultValue().isEmpty() ? " DEFAULT '" + field.getDefaultValue() + "'" : ""; + temp += !field.getOptionalParameter().isEmpty() ? " " + field.getOptionalParameter() : ""; + fields.add(temp); + return this; + } + + /** + * Create the table you wanted + * @return this class + */ + public TableGenerator create() { + StringBuilder sb = new StringBuilder(); + sb.append("CREATE TABLE IF NOT EXISTS " + tableName + " ( "); + AtomicBoolean used = new AtomicBoolean(false); + if (useID) sb.append(used.get() ? ", " : "").append("`id` INT(255) NOT NULL AUTO_INCREMENT");used.set(true); + fields.forEach(string -> { sb.append(used.get() ? ", " : "").append(string);used.set(true); }); + if (useID) sb.append(used.get() ? ", " : "").append("PRIMARY KEY (`id`)");used.set(true); + sb.append(" ) ENGINE = InnoDB;"); + connection.update(sb.toString()); + return this; + } + +} diff --git a/src/main/java/manager/DataBaseSelection.java b/src/main/java/manager/DataBaseSelection.java new file mode 100644 index 0000000..74874f2 --- /dev/null +++ b/src/main/java/manager/DataBaseSelection.java @@ -0,0 +1,160 @@ +package manager; + +import drivers.MySQLConnection; + +import java.sql.ResultSet; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.concurrent.atomic.AtomicBoolean; + +/******************************** + * @author Mathias Wagner + * Created 23.12.2020 + ********************************/ + +public class DataBaseSelection { + + private final MySQLConnection connection; + private final HashMap whereList; + private final ArrayList databaseParameters; + public ArrayList optionalQuery; + private int limit; + private String tableName; + + /** + * Basic constructor for selection + * @param connection The current Connection + * @param tableName The table name + */ + public DataBaseSelection(MySQLConnection connection, String tableName) { + this.whereList = new HashMap<>(); + this.databaseParameters = new ArrayList<>(); + this.optionalQuery = new ArrayList<>(); + this.connection = connection; + from(tableName); + } + + /** + * Basic constructor for selection + * @param connection The current Connection + */ + public DataBaseSelection(MySQLConnection connection) { + this.whereList = new HashMap<>(); + this.databaseParameters = new ArrayList<>(); + this.optionalQuery = new ArrayList<>(); + this.connection = connection; + } + + /** + * Get the temp-generated parameters + * @return ArrayList of parameters + */ + private ArrayList getTempParams() { + ArrayList tempParameters = new ArrayList<>(); + whereList.forEach((k, v) -> tempParameters.add(v)); + tempParameters.addAll(databaseParameters); + return tempParameters; + } + + /** + * Sets the table name + * @param tableName The table name + * @return this class + */ + public DataBaseSelection from(String tableName) { + this.tableName = connection.getTablePrefix().isEmpty() ? tableName : connection.getTablePrefix() + tableName; + return this; + } + + /** + * Adding another 'where'-statement + * @param column Table column name + * @param value Table value name + * @return this class + */ + public DataBaseSelection where(String column, Object value) { + whereList.put(column, value); + return this; + } + + /** + * Sets the limit of the rows + * @param limit The new limit + * @return this class + */ + public DataBaseSelection limit(int limit) { + this.limit = limit; + return this; + } + + /** + * Sets the limit of the rows + * @param limit The new limit + * @return this class + */ + public DataBaseSelection limit(String limit) { + this.limit = Integer.parseInt(limit); + return this; + } + + /** + * Get the ResultManager + * @return ResultManager + */ + public ResultManager getResult() { + return connection.getResult(processStatement(), getTempParams().toArray()); + } + + /** + * Get the ResultSet + * @return ResultSet + */ + public ResultSet getResultSet() { + return connection.getResultSet(processStatement(), getTempParams().toArray()); + } + + /** + * Debug the current Statement + * @return this class + */ + public DataBaseSelection printStatement() { + StringBuilder messageBuilder = new StringBuilder(); + messageBuilder.append(processStatement()); + messageBuilder.append(" | params» "); + AtomicBoolean added = new AtomicBoolean(false); + getTempParams().forEach(v -> { messageBuilder.append((added.get()) ? ", " : "").append(v);added.set(true); }); + StackTraceElement[] st = Thread.currentThread().getStackTrace(); + StackTraceElement stack = st[st.length-1]; + connection.getLogManager() + .sendInfo("DEBUG <" + stack.getFileName()+":"+stack.getLineNumber() + "> Statement: " + messageBuilder.toString()); + return this; + } + + /** + * Adding another factors + * @param query MySQL Query + * @param params Optional parameters for the Query + * @return this class + */ + public DataBaseSelection add(String query, Object... params) { + optionalQuery.add(query); + this.databaseParameters.addAll(Arrays.asList(params)); + return this; + } + + /** + * Get the current statement query + * @return the current statement query + */ + private String processStatement() { + StringBuilder sb = new StringBuilder(); + sb.append("SELECT * FROM ").append(tableName).append(" "); + AtomicBoolean used = new AtomicBoolean(false); + whereList.forEach((k, v) -> { if (!used.get()) sb.append("WHERE ");else sb.append("AND ");used.set(true);sb.append(k).append(" = ? "); }); + if (limit != 0) sb.append("LIMIT ").append(limit); + optionalQuery.forEach(v -> sb.append(" ").append(v).append(" ")); + return sb.toString(); + } + +} diff --git a/src/main/java/manager/ResultManager.java b/src/main/java/manager/ResultManager.java new file mode 100644 index 0000000..bf0d888 --- /dev/null +++ b/src/main/java/manager/ResultManager.java @@ -0,0 +1,117 @@ +package manager; + +import drivers.SqlLogManager; + +import java.sql.ResultSet; +import java.util.ArrayList; +import java.util.HashMap; + +/******************************** + * @author Mathias Wagner + * Created 23.12.2020 + ********************************/ + +public class ResultManager { + + private ResultSet resultSet; + private SqlLogManager logManager; + + /** + * Basic constructor for the ResultManager + * @param resultSet Existing ResultSet + * @param logManager Existing LogManager + */ + public ResultManager(ResultSet resultSet, SqlLogManager logManager) { + this.resultSet = resultSet; + this.logManager = logManager; + } + + /** + * Getting the ResultSet + * @return ResultSet + */ + public ResultSet getResultSet() { + return resultSet; + } + + /** + * Get the Object of an Result + * @param column Table column + * @return Object + */ + public Object getObject(String column) { + try { while (resultSet.next()) { return resultSet.getObject(column); } + } catch (Exception err) { logManager.sendError(err.getMessage()); } + return null; + } + + /** + * Get the String of an Result + * @param column Table column + * @return String + */ + public String getString(String column) { + try { while (resultSet.next()) { return resultSet.getString(column); } + } catch (Exception err) { logManager.sendError(err.getMessage()); } + return ""; + } + + /** + * Get the Integer of an Result + * @param column Table column + * @return Integer + */ + public Integer getInteger(String column) { + try { while (resultSet.next()) { return resultSet.getInt(column); } + } catch (Exception err) { logManager.sendError(err.getMessage()); } + return 0; + } + + /** + * Get the Boolean of an Result + * @param column Table column + * @return Boolean + */ + public Boolean getBoolean(String column) { + try { while (resultSet.next()) { return resultSet.getBoolean(column); } + } catch (Exception err) { logManager.sendError(err.getMessage()); } + return false; + } + + /** + * Get the count of the Result + * @return Integer (Count) + */ + public Integer getRowCount() { + int count=0; + try { while (resultSet.next()) { count++; } } catch (Exception err) { logManager.sendError(err.getMessage()); } + return count; + } + + /** + * Get a List of all Results + * @param column Table column + * @return ArrayList of Result + */ + public ArrayList getList(String column) { + ArrayList results = new ArrayList<>(); + try { while (resultSet.next()) { results.add(resultSet.getString(column)); } + } catch (Exception err) { logManager.sendError(err.getMessage()); } + return results; + } + + /** + * Get a List of all Results for 2 columns + * @param column Table column #1 + * @param column2 Table column #2 + * @return HashMap of Result + */ + public HashMap getMultipleList(String column, String column2) { + HashMap results = new HashMap<>(); + try { while (resultSet.next()) { + results.put(resultSet.getString(column), resultSet.getString(column2)); } + } catch (Exception err) { logManager.sendError(err.getMessage()); } + return results; + } + +} diff --git a/src/main/java/manager/UpdateManager.java b/src/main/java/manager/UpdateManager.java new file mode 100644 index 0000000..669fa3b --- /dev/null +++ b/src/main/java/manager/UpdateManager.java @@ -0,0 +1,206 @@ +package manager; + +import drivers.MySQLConnection; +import generator.TableGenerator; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.concurrent.atomic.AtomicBoolean; + +/******************************** + * @author Mathias Wagner + * Created 23.12.2020 + ********************************/ + +public class UpdateManager { + + private MySQLConnection connection; + private String tableName; + private HashMap whereList; + private HashMap setList; + + /** + * Basic constructor for the UpdateManager + * @param connection Existing MySQL connection + */ + public UpdateManager(MySQLConnection connection) { + this.connection = connection; + this.whereList = new HashMap<>(); + this.setList = new HashMap<>(); + } + + /** + * Basic constructor for the UpdateManager + * @param connection Existing MySQL connection + * @param tableName Table name + */ + public UpdateManager(MySQLConnection connection, String tableName){ + this.connection = connection; + toTable(tableName); + this.whereList = new HashMap<>(); + this.setList = new HashMap<>(); + } + + /** + * Get the parameters for the SQL statement + * @return the parameters + */ + private ArrayList getTempParams() { + ArrayList tempParams = new ArrayList<>(); + setList.forEach((str, obj) -> tempParams.add(obj)); + whereList.forEach((str, obj) -> tempParams.add(obj)); + return tempParams; + } + + /** + * Get the current connection + * @return MySQL connection + */ + public MySQLConnection getConnection() { + return connection; + } + + /** + * Print the deletion statement + * @return this class + */ + public UpdateManager printDeleteStatement() { + StringBuilder messageBuilder = new StringBuilder(); + messageBuilder.append(processDeleteStatement()); + messageBuilder.append(" | params» "); + AtomicBoolean added = new AtomicBoolean(false); + whereList.values().forEach(v -> { messageBuilder.append((added.get()) ? ", " : "").append(v);added.set(true); }); + StackTraceElement[] st = Thread.currentThread().getStackTrace(); + StackTraceElement stack = st[st.length-1]; + connection.getLogManager() + .sendInfo("DEBUG <" + stack.getFileName()+":"+stack.getLineNumber() + "> Statement: " + messageBuilder.toString()); + return this; + } + + /** + * Print the update statement + * @return this class + */ + public UpdateManager printUpdateStatement() { + StringBuilder messageBuilder = new StringBuilder(); + messageBuilder.append(processUpdateStatement()); + messageBuilder.append(" | params» "); + AtomicBoolean added = new AtomicBoolean(false); + getTempParams().forEach(v -> { messageBuilder.append((added.get()) ? ", " : "").append(v);added.set(true); }); + StackTraceElement[] st = Thread.currentThread().getStackTrace(); + StackTraceElement stack = st[st.length-1]; + connection.getLogManager() + .sendInfo("DEBUG <" + stack.getFileName()+":"+stack.getLineNumber() + "> Statement: " + messageBuilder.toString()); + return this; + } + + /** + * Change the tableName + * @param tableName New tableName + * @return this class + */ + public UpdateManager toTable(String tableName) { + this.tableName = connection.getTablePrefix().isEmpty() ? tableName : connection.getTablePrefix() + tableName; + return this; + } + + /** + * Add a 'where'-clause + * @param column Table column + * @param value Value of the column + * @return this class + */ + public UpdateManager where(String column, Object value) { + whereList.put(column, value); + return this; + } + + /** + * Add a 'set'-clause + * @param column Table column + * @param value Value of the column + * @return this class + */ + public UpdateManager set(String column, Object value) { + setList.put(column, value); + return this; + } + + /** + * Delete the entries with your current conditions + * @return this class + */ + public UpdateManager delete() { + connection.update(processDeleteStatement(), whereList.values().toArray()); + return this; + } + + /** + * Update the entries with your current conditions + * @return this class + */ + public UpdateManager update() { + connection.update(processUpdateStatement(), getTempParams().toArray()); + return this; + } + + /** + * Get the Query of the 'update'-Statement + * @return the Statement + */ + private String processUpdateStatement() { + StringBuilder sb = new StringBuilder(); + sb.append("UPDATE ").append(tableName); + if (!setList.isEmpty()) sb.append(" SET "); + AtomicBoolean used = new AtomicBoolean(false); + setList.forEach((str, obj) -> { + if (used.get()) sb.append(", "); + sb.append(str).append(" = ?"); + used.set(true); + }); + if (!whereList.isEmpty()) sb.append(" WHERE "); + AtomicBoolean used2 = new AtomicBoolean(false); + whereList.forEach((str, obj) -> { + if (used2.get()) sb.append(" AND "); + sb.append(str).append(" = ?"); + used2.set(true); + }); + return sb.toString(); + } + + /** + * Get the Query of the 'delete'-Statement + * @return + */ + private String processDeleteStatement() { + StringBuilder sb = new StringBuilder(); + sb.append("DELETE FROM ").append(tableName); + if (!whereList.isEmpty()) sb.append(" WHERE "); + AtomicBoolean used = new AtomicBoolean(false); + whereList.forEach((str, obj) -> { + if (used.get()) sb.append(" AND "); + sb.append(str).append(" = ?"); + used.set(true); + }); + return sb.toString(); + } + + + /** + * Generate a new Table (with prefilled tableName) + * @param tableName Name of the new table + * @return the generator + */ + public TableGenerator generateTable(String tableName) { + return new TableGenerator(this, tableName); + } + + /** + * Generate a new Table + * @return the generator + */ + public TableGenerator generateTable() { + return (tableName.isEmpty()) ? null : new TableGenerator(this, tableName); + } + +} diff --git a/src/main/java/types/LogLevelType.java b/src/main/java/types/LogLevelType.java new file mode 100644 index 0000000..5aaf392 --- /dev/null +++ b/src/main/java/types/LogLevelType.java @@ -0,0 +1,20 @@ +package types; + +/******************************** + * @author Mathias Wagner + * Created 23.12.2020 + ********************************/ + +public enum LogLevelType { + + NONE("Sends nothing"), + LOW("Sends Warnings & Errors"), + ALL("Sends Infos, Warnings & Errors"); + + /** + * Basic constructor for the LogLevelType enum + * @param info Info for documentation + */ + LogLevelType(String info) { } + +} diff --git a/src/main/java/types/LoginParam.java b/src/main/java/types/LoginParam.java new file mode 100644 index 0000000..146edf0 --- /dev/null +++ b/src/main/java/types/LoginParam.java @@ -0,0 +1,37 @@ +package types; + +/******************************** + * @author Mathias Wagner + * Created 23.12.2020 + ********************************/ + +public enum LoginParam { + + DEFAULT("useSSL=false&autoReconnect=true&useUnicode=yes&characterEncoding=UTF-8&useTimezone=true&serverTimezone=UTC"), + NO_SSL("useSSL=false"), + USE_SSL("useSSL=true"), + AUTO_RECONNECT("autoReconnect=true"), + UTF8_ENCODING("characterEncoding=UTF-8"), + USE_UNICODE("useUnicode=yes"), + USE_TIMEZONE("useTimezone=true"), + TIMEZONE_UTC("serverTimezone=UTC"); + + private String value; + + /** + * Basic constructor for the LoginParam enum + * @param value JDBC parameter + */ + LoginParam(String value) { + this.value = value; + } + + /** + * Get the JDBC value + * @return the value + */ + public String getValue() { + return this.value; + } + +} diff --git a/src/main/java/types/SQLType.java b/src/main/java/types/SQLType.java new file mode 100644 index 0000000..11dd0b0 --- /dev/null +++ b/src/main/java/types/SQLType.java @@ -0,0 +1,28 @@ +package types; + +public enum SQLType { + + STRING("VARCHAR"), + INTEGER("INT"), + DATE("DATE"), + DATETIME("DATETIME"); + + private String value = ""; + + /** + * Basic constructor for the SQLType enum + * @param value MySQL data type + */ + SQLType(String value) { + this.value = value; + } + + /** + * Get the value of the chosen enum + * @return + */ + public String getValue() { + return value; + } + +}