diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..086dfce --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1 @@ +ko_fi: gnmyt \ No newline at end of file diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..fdb2371 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,17 @@ +name: Java CI + +on: [push] + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v2 + - name: Set up JDK + uses: actions/setup-java@v2 + with: + java-version: '11' + distribution: 'adopt' + - name: Build with Maven + run: mvn --batch-mode --update-snapshots verify \ No newline at end of file diff --git a/.gitignore b/.gitignore index bcbe4c5..c4016ca 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ /sqltoolkit.iml /.idea/ +/target \ No newline at end of file diff --git a/README.md b/README.md index b915628..898afc3 100644 --- a/README.md +++ b/README.md @@ -15,116 +15,128 @@

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/gnmyt/sqltoolkit.git +This is a small project for quickly managing a MySQL database in Java. It makes your everyday life with a database much +easier. + +### Installation + +1. Add the jitpack repository to your `pom.xml` + ```xml + + + jitpack.io + https://jitpack.io + + + ``` +2. Add the dependency to your `pom.xml` + ```xml + + com.github.gnmyt + sqltoolkit + master-SNAPSHOT + ``` -2. Move the project into a package of your project (in most cases "sql") -3. Ready! Have fun -#### Maven coming soon ### Usage Examples + 1. Create a connection - - Example of a constructor without optional specifications + - Example of creating a connection ```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"); - ``` +2. Perform a default SQL query + - Get a ResultSet + ```java + connection.getResultSet("SELECT * FROM example WHERE test = ?", "test1"); + ``` + - Perform an update + ```java + connection.update("UPDATE example SET test = ? WHERE abc = ?", "test1", "test2"); + ``` 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") + 1. Getting a string from the table + ```java + String value = connection.getResult("query", "parameters") + .getString("column"); + ``` + 2. Getting a list from the table + ```java + ArrayList list = connection.getResult("query", "parameters") + .getList("column"); + ``` + or + ```java + ArrayList> list = connection.getResult("query", "parameters") + .getList(); + ``` + 4. Choosing Results + ```java + connection + .selectFrom("table") .where("column", "value") - .add("LIMIT 2,5") - .printStatement(); - ``` + .limit(10) + .getResult(); + ``` 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(); - ``` - - + 1. Update a Table + ```java + connection + .updateTo("table") + .where("column", "value") + .set("column", "newValue") + .execute(); + ``` + 2. Generate a Table + ```java + connection + .generateTable("table") + .addField(SQLType.STRING, "column") + .addField(SQLType.INTEGER, "column2", 2) + .create(); + ``` + 3. Delete something from a table + ```java + connection + .deleteFrom("table") + .where("column", "value") + .execute(); + ``` + 4. Insert something into a table + ```java + connection + .insertTo("table") + .value("username", "GNM") + .value("email", "germannewsmaker@gmail.com") + .execute(); + ``` +You can find other examples in the [examples directory](src/examples/java). + ## 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! + +Currently, there are not many features, so feel free to write me some suggestions! [contributors-shield]: https://img.shields.io/github/contributors/gnmyt/sqltoolkit.svg?style=for-the-badge + [contributors-url]: https://github.com/gnmyt/sqltoolkit/graphs/contributors + [forks-shield]: https://img.shields.io/github/forks/gnmyt/sqltoolkit.svg?style=for-the-badge + [forks-url]: https://github.com/gnmyt/sqltoolkit/network/members + [stars-shield]: https://img.shields.io/github/stars/gnmyt/sqltoolkit.svg?style=for-the-badge + [stars-url]: https://github.com/gnmyt/sqltoolkit/stargazers + [issues-shield]: https://img.shields.io/github/issues/gnmyt/sqltoolkit.svg?style=for-the-badge + [issues-url]: https://github.com/gnmyt/sqltoolkit/issues + [license-shield]: https://img.shields.io/github/license/gnmyt/sqltoolkit.svg?style=for-the-badge -[license-url]: https://github.com/gnmyt/sqltoolkit/blob/master/LICENSE.txt + +[license-url]: https://github.com/gnmyt/sqltoolkit/blob/master/LICENSE \ No newline at end of file diff --git a/pom.xml b/pom.xml index 8ef4ba1..c856848 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ de.gnmyt SQLToolkit - 1.0 + 2.0 8 @@ -14,11 +14,28 @@ + + mysql mysql-connector-java 8.0.25 + + + + org.slf4j + slf4j-api + 1.7.32 + + + + + org.slf4j + slf4j-simple + 1.7.32 + + \ No newline at end of file diff --git a/src/examples/java/LoginExample.java b/src/examples/java/LoginExample.java new file mode 100644 index 0000000..5534e19 --- /dev/null +++ b/src/examples/java/LoginExample.java @@ -0,0 +1,26 @@ +import de.gnmyt.sqltoolkit.drivers.MySQLConnection; + +public class LoginExample { + + public static void main(String[] args) { + + // First we can define the mysql server data into some variables + String hostname = "localhost"; + String username = "root"; + String password = "password"; + String database = "database"; + + // Then we need to create a connection + MySQLConnection connection = new MySQLConnection(hostname, username, password, database); // Here you need to provide your mysql server data + + // You can now set the settings of the connection (before connecting) + connection.updateSettings() + .useSSL(true) // You can set for example the ssl property + .customProperty("example", "value"); // You can also set a custom property + + + // Now you can connect to the database + connection.connect(); + } + +} diff --git a/src/examples/java/QueryExample.java b/src/examples/java/QueryExample.java new file mode 100644 index 0000000..572c3e9 --- /dev/null +++ b/src/examples/java/QueryExample.java @@ -0,0 +1,60 @@ +import de.gnmyt.sqltoolkit.drivers.MySQLConnection; +import de.gnmyt.sqltoolkit.queries.DeletionQuery; +import de.gnmyt.sqltoolkit.queries.InsertQuery; +import de.gnmyt.sqltoolkit.queries.SelectionQuery; +import de.gnmyt.sqltoolkit.querybuilder.QueryParameter; +import de.gnmyt.sqltoolkit.querybuilder.SQLQuery; + +import java.util.HashMap; + +public class QueryExample { + + public static void main(String[] args) { + + // First we need to connect to our database + MySQLConnection connection = new MySQLConnection("localhost", "root", "password", "database"); + + // We then can create a hashmap with all where-parameters + HashMap whereList = new HashMap<>(); + + // Now we can add some values to the 'where'-list + whereList.put("username", "GNM"); + whereList.put("email", "germannewsmaker@gmail.com"); + + // Now we can create an example 'select'-query + SQLQuery query = connection.createQuery(SelectionQuery.class) // Here you can provide which query you want to create + .addParameter(QueryParameter.TABLE_NAME, "example_table") // Now we can pass in the table name + .addParameter(QueryParameter.WHERE_LIST, whereList) // And the list of 'where'-parameters + .build(); // Then we build the query + + // You can then execute it + connection.getResult(query); + + // Or print it + System.out.println(query); + + // You can also create a 'delete'-query + + SQLQuery deleteQuery = connection.createQuery(DeletionQuery.class) // Now we try the deletion query + .addParameter(QueryParameter.TABLE_NAME, "example_table") // Here you can pass in the table name + .addParameter(QueryParameter.WHERE_LIST, whereList) // For the example we are using the same list as before + .build(); // And now we build the query + + // You can also create for example a 'insert'-query + + // Because we want to insert values into a table we first need to create the list of values + HashMap insertValues = new HashMap<>(); + + // Now we can put add some values to the 'insert'-list + insertValues.put("username", "GNM"); + insertValues.put("email", "germannewsmaker@gmail.com"); + insertValues.put("password", "example123!"); + + // And then we can create the query + SQLQuery insertQuery = connection.createQuery(InsertQuery.class) // Now we try the insert query + .addParameter(QueryParameter.TABLE_NAME, "example_table") // Here you can pass in the table name + .addParameter(QueryParameter.VALUE_LIST, insertValues) // And now we pass in the value list + .build(); + } + +} diff --git a/src/examples/java/StorageMediumExample.java b/src/examples/java/StorageMediumExample.java new file mode 100644 index 0000000..28610aa --- /dev/null +++ b/src/examples/java/StorageMediumExample.java @@ -0,0 +1,80 @@ +import de.gnmyt.sqltoolkit.drivers.MySQLConnection; +import de.gnmyt.sqltoolkit.storage.SQLStorageMedium; + +public class StorageMediumExample { + + public static void main(String[] args) { + + // First we need to connect to the mysql database + MySQLConnection connection = new MySQLConnection("localhost", "root", "password", "database").connect(); + + // Then we can register our user table + connection.getTableFactory().register(new StorageMediumExample.ConfigurationStorage(connection)); + + // Now we can get the storage from our table factory + ConfigurationStorage storage = (ConfigurationStorage) connection.getTableFactory().getStorage(ConfigurationStorage.class); + + // Here we can use the methods that we created in the storage + storage.updateLanguage("en"); + storage.updateVersion("1.0"); + + // We can also get a value by using the storage medium + String version = storage.getVersion(); + + // If you want to you can list all entries from the current storage + storage.getEntries().forEach(entry -> + System.out.println(entry.get("keyName") + " -> " + entry.get("value"))); + } + + + public static class ConfigurationStorage extends SQLStorageMedium { + + public ConfigurationStorage(MySQLConnection connection) { + super(connection); + } + + @Override + protected String tableName() { + return "config_storage"; + } + + // Here we can add some example methods to test the storage medium + + /** + * Updates the language of the configuration storage + * + * @param newLanguage The new language + */ + public void updateLanguage(String newLanguage) { + insertOrUpdate("language", newLanguage); + } + + /** + * Gets the current language of the configuration storage + * + * @return The current language of the configuration storage + */ + public String getLanguage() { + return get("language"); + } + + /** + * Updates the version of the configuration storage + * + * @param newVersion The new version + */ + public void updateVersion(String newVersion) { + insertOrUpdate("version", newVersion); + } + + /** + * Gets the current version of the configuration storage + * + * @return The current version of the configuration storage + */ + public String getVersion() { + return get("version"); + } + } + +} diff --git a/src/examples/java/TableExample.java b/src/examples/java/TableExample.java new file mode 100644 index 0000000..7e60ce5 --- /dev/null +++ b/src/examples/java/TableExample.java @@ -0,0 +1,96 @@ +import de.gnmyt.sqltoolkit.drivers.MySQLConnection; +import de.gnmyt.sqltoolkit.storage.SQLTable; +import de.gnmyt.sqltoolkit.types.SQLType; +import de.gnmyt.sqltoolkit.types.TableField; + +public class TableExample { + + private static MySQLConnection connection; + + public static void main(String[] args) { + + // First we need to connect to the mysql database + connection = new MySQLConnection("localhost", "root", "password", "database").connect(); + + // Then we can register our user table + connection.getTableFactory().register(new UserTable(connection)); + + // Now let's create some users + createUser("GNM", "germannewsmaker@gmail.com", "Mathias"); + + createUser("delete_me", "deleteme@example.com", "DeleteMe"); + + // Here we can get the email of our user before we delete him + String email = getUserMail("delete_me"); + + // Now we can delete this user + deleteUser("delete_me"); + } + + /** + * Creates a user in the user table + * + * @param username The name of the user (nickname) + * @param email The email of the user + * @param first_name The first name of the user + */ + public static void createUser(String username, String email, String first_name) { + SQLTable userTable = connection.getTableFactory().getTable(UserTable.class); + + userTable.insert() + .value("username", username) + .value("email", email) + .value("first_name", first_name) + .execute(); + } + + /** + * Deletes a user from the user table + * + * @param username The name of the user + */ + public static void deleteUser(String username) { + SQLTable userTable = connection.getTableFactory().getTable(UserTable.class); + + userTable.delete() + .where("username", username) + .execute(); + } + + /** + * Gets the email of the user + * + * @param username The name of the user + * @return the email of the user + */ + public static String getUserMail(String username) { + SQLTable userTable = connection.getTableFactory().getTable(UserTable.class); + + return userTable.select() + .where("username", username) + .getResult() + .getString("email"); + } + + public static class UserTable extends SQLTable { + + public UserTable(MySQLConnection connection) { + super(connection); + } + + @Override + protected String tableName() { + return "users"; + } + + @Override + protected void tableFields() { + string("username", 255, ""); + custom(new TableField().setType(SQLType.STRING).setName("email").setLength(25).setDefaultValue("test@example.com")); + custom("password").type(SQLType.STRING).allowNull(true).length(80).add(); + custom().name("first_name").add(); + } + + } + +} diff --git a/src/main/java/de/gnmyt/SQLToolkit/api/SQLConsumer.java b/src/main/java/de/gnmyt/SQLToolkit/api/SQLConsumer.java deleted file mode 100644 index c37ee53..0000000 --- a/src/main/java/de/gnmyt/SQLToolkit/api/SQLConsumer.java +++ /dev/null @@ -1,13 +0,0 @@ -package de.gnmyt.SQLToolkit.api; - -import java.sql.SQLException; - -/******************************** - * @author Mathias Wagner - * Created 25.12.2020 - *******************************/ - -@FunctionalInterface -public interface SQLConsumer { - void accept(T t) throws SQLException; -} diff --git a/src/main/java/de/gnmyt/SQLToolkit/drivers/MySQLConnection.java b/src/main/java/de/gnmyt/SQLToolkit/drivers/MySQLConnection.java deleted file mode 100755 index 896685f..0000000 --- a/src/main/java/de/gnmyt/SQLToolkit/drivers/MySQLConnection.java +++ /dev/null @@ -1,286 +0,0 @@ -package de.gnmyt.SQLToolkit.drivers; - -import de.gnmyt.SQLToolkit.api.SQLConsumer; -import de.gnmyt.SQLToolkit.manager.InsertManager; -import de.gnmyt.SQLToolkit.manager.ResultManager; -import de.gnmyt.SQLToolkit.manager.DataBaseSelection; -import de.gnmyt.SQLToolkit.manager.UpdateManager; -import de.gnmyt.SQLToolkit.types.LogLevelType; -import de.gnmyt.SQLToolkit.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 : 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); - } - - /** - * Run a action with a result from your server - * @param query Search query - * @param consumer consumer - * @param params Optional parameters - */ - public void getResult(String query, SQLConsumer consumer, Object... params) { - try { - ResultSet resultSet = getResultSet(query, params); - consumer.accept(resultSet); - resultSet.close(); - } catch (Exception ignored) {} - } - - /** - * 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 : 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 de.gnmyt.SQLToolkit.manager for easier updating - * @return Update de.gnmyt.SQLToolkit.manager - */ - public UpdateManager update() { - return new UpdateManager(this); - } - - /** - * Get the update de.gnmyt.SQLToolkit.manager for easier updating (pre filled table) - * @param tableName The name of the table - * @return Update de.gnmyt.SQLToolkit.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); - } - - /** - * Get the InsertManager for easier inserting to a table - * @return InsertManager - */ - public InsertManager insert() { - return new InsertManager(this); - } - - /** - * Get the InsertManager for easier inserting to a table - * @param tableName The name of the table you want to insert a object - * @return InsertManager - */ - public InsertManager insertTo(String tableName) { - return new InsertManager(this, tableName); - } - - /** - * 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().contains("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/de/gnmyt/SQLToolkit/drivers/SqlLogManager.java b/src/main/java/de/gnmyt/SQLToolkit/drivers/SqlLogManager.java deleted file mode 100755 index 8cfc8f0..0000000 --- a/src/main/java/de/gnmyt/SQLToolkit/drivers/SqlLogManager.java +++ /dev/null @@ -1,92 +0,0 @@ -package de.gnmyt.SQLToolkit.drivers; - -import de.gnmyt.SQLToolkit.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/de/gnmyt/SQLToolkit/fields/SQLField.java b/src/main/java/de/gnmyt/SQLToolkit/fields/SQLField.java deleted file mode 100644 index 1fb48c0..0000000 --- a/src/main/java/de/gnmyt/SQLToolkit/fields/SQLField.java +++ /dev/null @@ -1,110 +0,0 @@ -package de.gnmyt.SQLToolkit.fields; - -import de.gnmyt.SQLToolkit.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/de/gnmyt/SQLToolkit/generator/TableGenerator.java b/src/main/java/de/gnmyt/SQLToolkit/generator/TableGenerator.java deleted file mode 100644 index 13dd9bb..0000000 --- a/src/main/java/de/gnmyt/SQLToolkit/generator/TableGenerator.java +++ /dev/null @@ -1,84 +0,0 @@ -package de.gnmyt.SQLToolkit.generator; - -import de.gnmyt.SQLToolkit.drivers.MySQLConnection; -import de.gnmyt.SQLToolkit.fields.SQLField; -import de.gnmyt.SQLToolkit.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 de.gnmyt.SQLToolkit.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/de/gnmyt/SQLToolkit/manager/DataBaseSelection.java b/src/main/java/de/gnmyt/SQLToolkit/manager/DataBaseSelection.java deleted file mode 100644 index dd22b42..0000000 --- a/src/main/java/de/gnmyt/SQLToolkit/manager/DataBaseSelection.java +++ /dev/null @@ -1,160 +0,0 @@ -package de.gnmyt.SQLToolkit.manager; - -import de.gnmyt.SQLToolkit.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/de/gnmyt/SQLToolkit/manager/InsertManager.java b/src/main/java/de/gnmyt/SQLToolkit/manager/InsertManager.java deleted file mode 100644 index fefa061..0000000 --- a/src/main/java/de/gnmyt/SQLToolkit/manager/InsertManager.java +++ /dev/null @@ -1,87 +0,0 @@ -package de.gnmyt.SQLToolkit.manager; - -import de.gnmyt.SQLToolkit.drivers.MySQLConnection; - -import java.util.HashMap; -import java.util.concurrent.atomic.AtomicBoolean; - -public class InsertManager { - - private MySQLConnection connection; - private String tableName; - private HashMap values; - - /** - * Basic constructor for the InsertManager - * @param connection The current connection - */ - public InsertManager(MySQLConnection connection) { - this.connection = connection; - values = new HashMap<>(); - } - - /** - * Constructor with direct tableName integration - * @param connection The current connection - * @param tableName The name of the table - */ - public InsertManager(MySQLConnection connection, String tableName) { - this.connection = connection; - this.tableName = tableName; - values = new HashMap<>(); - } - - /** - * Optionally add the tableName / Change the name of the table - * @param tableName The name of the table - */ - public void from(String tableName) { - this.tableName = tableName; - } - - /** - * Query value - * @param fieldName The name of the column - * @param value The value of the object you want to insert - * @return this class - */ - public InsertManager value(String fieldName, Object value) { - values.put(fieldName, value); - return this; - } - - /** - * Prepares the SQL Query - * @return the SQL Query - */ - public String prepareStatement() { - StringBuilder query = new StringBuilder(); - query.append("INSERT INTO ").append(tableName).append(" ").append("("); - AtomicBoolean used = new AtomicBoolean(false); - values.forEach((field, object) -> { - if (used.get()) query.append(", "); - used.set(true); - query.append("`").append(field).append("`"); - }); - query.append(")"); - if (values.size() > 0) query.append(" VALUES ("); - AtomicBoolean used_values = new AtomicBoolean(false); - for (int i=0; i < values.size(); i++) { - if (used_values.get()) query.append(", "); - used_values.set(true); - query.append("?"); - } - if (values.size() > 0) query.append(")"); - return query.toString(); - } - - /** - * Execute the current SQL query - * @return this class - */ - public InsertManager execute() { - connection.update(prepareStatement(), values.values().toArray()); - return this; - } - -} diff --git a/src/main/java/de/gnmyt/SQLToolkit/manager/UpdateManager.java b/src/main/java/de/gnmyt/SQLToolkit/manager/UpdateManager.java deleted file mode 100644 index 27d1d8c..0000000 --- a/src/main/java/de/gnmyt/SQLToolkit/manager/UpdateManager.java +++ /dev/null @@ -1,206 +0,0 @@ -package de.gnmyt.SQLToolkit.manager; - -import de.gnmyt.SQLToolkit.drivers.MySQLConnection; -import de.gnmyt.SQLToolkit.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 de.gnmyt.SQLToolkit.generator - */ - public TableGenerator generateTable(String tableName) { - return new TableGenerator(this, tableName); - } - - /** - * Generate a new Table - * @return the de.gnmyt.SQLToolkit.generator - */ - public TableGenerator generateTable() { - return (tableName.isEmpty()) ? null : new TableGenerator(this, tableName); - } - -} diff --git a/src/main/java/de/gnmyt/SQLToolkit/types/LogLevelType.java b/src/main/java/de/gnmyt/SQLToolkit/types/LogLevelType.java deleted file mode 100644 index 7ab21d8..0000000 --- a/src/main/java/de/gnmyt/SQLToolkit/types/LogLevelType.java +++ /dev/null @@ -1,20 +0,0 @@ -package de.gnmyt.SQLToolkit.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/de/gnmyt/SQLToolkit/types/LoginParam.java b/src/main/java/de/gnmyt/SQLToolkit/types/LoginParam.java deleted file mode 100644 index b67166f..0000000 --- a/src/main/java/de/gnmyt/SQLToolkit/types/LoginParam.java +++ /dev/null @@ -1,37 +0,0 @@ -package de.gnmyt.SQLToolkit.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/de/gnmyt/SQLToolkit/types/SQLType.java b/src/main/java/de/gnmyt/SQLToolkit/types/SQLType.java deleted file mode 100644 index 2c9adb4..0000000 --- a/src/main/java/de/gnmyt/SQLToolkit/types/SQLType.java +++ /dev/null @@ -1,28 +0,0 @@ -package de.gnmyt.SQLToolkit.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; - } - -} diff --git a/src/main/java/de/gnmyt/sqltoolkit/api/SQLConsumer.java b/src/main/java/de/gnmyt/sqltoolkit/api/SQLConsumer.java new file mode 100644 index 0000000..24be0a0 --- /dev/null +++ b/src/main/java/de/gnmyt/sqltoolkit/api/SQLConsumer.java @@ -0,0 +1,8 @@ +package de.gnmyt.sqltoolkit.api; + +import java.sql.SQLException; + +@FunctionalInterface +public interface SQLConsumer { + void accept(T t) throws SQLException; +} diff --git a/src/main/java/de/gnmyt/sqltoolkit/drivers/MySQLConnection.java b/src/main/java/de/gnmyt/sqltoolkit/drivers/MySQLConnection.java new file mode 100755 index 0000000..fcdddae --- /dev/null +++ b/src/main/java/de/gnmyt/sqltoolkit/drivers/MySQLConnection.java @@ -0,0 +1,351 @@ +package de.gnmyt.sqltoolkit.drivers; + +import de.gnmyt.sqltoolkit.api.SQLConsumer; +import de.gnmyt.sqltoolkit.factory.TableFactory; +import de.gnmyt.sqltoolkit.generator.TableGenerator; +import de.gnmyt.sqltoolkit.manager.*; +import de.gnmyt.sqltoolkit.querybuilder.AbstractQuery; +import de.gnmyt.sqltoolkit.querybuilder.QueryBuilder; +import de.gnmyt.sqltoolkit.querybuilder.SQLQuery; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; + +public class MySQLConnection { + + public static final Logger LOG = LoggerFactory.getLogger("MySQL-Logger"); + private final TableFactory tableFactory = new TableFactory(this); + private final ConnectSettingsManager settingsManager = new ConnectSettingsManager(this); + + private final String hostname; + private final String username; + private final String password; + private final String database; + + private Connection con; + + /** + * 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 + */ + public MySQLConnection(String hostname, String username, String password, String database) { + this.hostname = hostname; + this.username = username; + this.password = password; + this.database = database; + } + + public ConnectSettingsManager updateSettings() { + return settingsManager; + } + + /** + * Get a result from your server + * + * @param query Search query + * @param params Optional parameters + * @return ResultSet + */ + public ResultSet getResultSet(String query, Object... params) { + try { + PreparedStatement ps = con.prepareStatement(query); + + for (int i = 0; i < params.length; i++) { + ps.setObject(i + 1, params[i]); + } + + return ps.executeQuery(); + } catch (Exception err) { + LOG.error(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)); + } + + /** + * Run an action with a result from your server + * + * @param query The search query + * @param consumer The consumer + * @param params The optional parameters + */ + public void getResultSet(String query, SQLConsumer consumer, Object... params) { + try { + consumer.accept(getResultSet(query, params)); + } catch (Exception e) { + LOG.error(e.getMessage()); + } + } + + /** + * Run an action with a result from your server + * + * @param query The search query + * @param consumer The consumer + * @param params The optional parameters + */ + public void getResult(String query, SQLConsumer consumer, Object... params) { + try { + consumer.accept(getResult(query, params)); + } catch (Exception e) { + LOG.error(e.getMessage()); + } + } + + /** + * Gets a {@link ResultSet} from the server + * + * @param query The query you want to execute + * @return the {@link ResultSet} + */ + public ResultSet getResultSet(SQLQuery query) { + return getResultSet(query.getStatement(), query.getParameters()); + } + + /** + * Gets a {@link ResultManager} from the server + * + * @param query The query you want to execute + * @return the {@link ResultManager} + */ + public ResultManager getResult(SQLQuery query) { + return getResult(query.getStatement(), query.getParameters()); + } + + /** + * Run an action with the result from your server + * + * @param query The query you want to execute + * @param consumer The consumer you want to execute + */ + public void getResultSet(SQLQuery query, SQLConsumer consumer) { + try { + consumer.accept(getResultSet(query)); + } catch (Exception e) { + LOG.error(e.getMessage()); + } + } + + /** + * Run an action with the result from your server (get the manager) + * + * @param query The query you want to execute + * @param consumer The consumer you want to execute + */ + public void getResult(SQLQuery query, SQLConsumer consumer) { + try { + consumer.accept(getResult(query)); + } catch (Exception e) { + LOG.error(e.getMessage()); + } + } + + /** + * Gets a new instance of the {@link QueryBuilder} + * + * @param queryType The type of the query you want to generate + * @return a new {@link QueryBuilder} instance + */ + public QueryBuilder createQuery(Class queryType) { + return new QueryBuilder(queryType); + } + + /** + * 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) { + try { + PreparedStatement ps = con.prepareStatement(query); + + for (int i = 0; i < params.length; i++) { + ps.setObject(i + 1, params[i]); + } + + ps.executeUpdate(); + } catch (Exception err) { + err.printStackTrace(); + } + return this; + } + + /** + * Update something on your server by query + * + * @param query The query you want to execute + * @return this class + */ + public MySQLConnection update(SQLQuery query) { + return update(query.getStatement(), query.getParameters()); + } + + /** + * Gets the {@link UpdateManager} for easier updating + * + * @return the {@link UpdateManager} + */ + public UpdateManager update() { + return new UpdateManager(this); + } + + /** + * Gets the {@link UpdateManager} for easier updating (pre-filled table) + * + * @param tableName The name of the table + * @return the {@link UpdateManager} + */ + public UpdateManager updateTo(String tableName) { + return new UpdateManager(this, tableName); + } + + /** + * Gets the {@link SelectionManager} for easier selection of tables + * + * @return The {@link SelectionManager} + */ + public SelectionManager select() { + return new SelectionManager(this); + } + + /** + * Gets the {@link SelectionManager} for easier selection of tables (pre-filled table) + * + * @param tableName The name of the table + * @return the {@link SelectionManager} + */ + public SelectionManager selectFrom(String tableName) { + return new SelectionManager(this, tableName); + } + + /** + * Gets the {@link InsertManager} for easier inserting to a table + * + * @return the {@link InsertManager} + */ + public InsertManager insert() { + return new InsertManager(this); + } + + /** + * Gets the {@link InsertManager} for easier inserting to a table + * + * @param tableName The name of the table you want to insert a object + * @return the {@link InsertManager} + */ + public InsertManager insertTo(String tableName) { + return new InsertManager(this, tableName); + } + + /** + * Gets the {@link DeletionManager} for easier deleting rows in a table + * + * @return the {@link DeletionManager} + */ + public DeletionManager delete() { + return new DeletionManager(this); + } + + /** + * Gets the {@link DeletionManager} for easier deleting rows in a table + * + * @param tableName The name of the table you want to delete a row from + * @return the {@link DeletionManager} + */ + public DeletionManager deleteFrom(String tableName) { + return new DeletionManager(this, tableName); + } + + /** + * Gets the table generator + * + * @param tableName The name of the table + * @return the instance of the table generator + */ + public TableGenerator generateTable(String tableName) { + return new TableGenerator(this, tableName); + } + + /** + * Gets the table factory + * + * @return the table factory + */ + public TableFactory getTableFactory() { + return tableFactory; + } + + /** + * Connect with your MySQL server + * + * @return this class + */ + public MySQLConnection connect() { + if (!isConnected()) { + try { + LOG.info("Connecting to " + hostname + " with user " + username + " to database " + database); + Class.forName("com.mysql.cj.jdbc.Driver"); + con = DriverManager.getConnection("jdbc:mysql://" + hostname + "/" + database + settingsManager.generateConnectionString(), username, password); + LOG.info("Connection established"); + } catch (Exception exception) { + if (exception.getMessage().contains("jdbc.Driver")) + LOG.error("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")) + LOG.error("No packets received from the server."); + else if (exception.getMessage().contains("denied for user")) + LOG.error("Wrong username/password"); + else LOG.error(exception.getMessage()); + } + } else LOG.warn("Already connected"); + return this; + } + + /** + * Disconnect from your MySQL Server + * + * @return this class + */ + public MySQLConnection disconnect() { + if (isConnected()) { + try { + con.close(); + con = null; + LOG.info("Connection closed"); + } catch (Exception err) { + LOG.error(err.getMessage()); + } + } else LOG.warn("Not connected. Please connect first"); + return this; + } + + /** + * Check if you are connected + * + * @return status of the connection + */ + public boolean isConnected() { + return (con != null); + } + + +} diff --git a/src/main/java/de/gnmyt/sqltoolkit/factory/TableFactory.java b/src/main/java/de/gnmyt/sqltoolkit/factory/TableFactory.java new file mode 100644 index 0000000..6638f59 --- /dev/null +++ b/src/main/java/de/gnmyt/sqltoolkit/factory/TableFactory.java @@ -0,0 +1,56 @@ +package de.gnmyt.sqltoolkit.factory; + +import de.gnmyt.sqltoolkit.drivers.MySQLConnection; +import de.gnmyt.sqltoolkit.storage.SQLStorageMedium; +import de.gnmyt.sqltoolkit.storage.SQLTable; + +import java.util.HashMap; + +public class TableFactory { + + private final HashMap, SQLTable> REGISTERED_TABLES = new HashMap<>(); + + private final MySQLConnection connection; + + /** + * Basic constructor of the {@link TableFactory} + * + * @param connection The mysql connection + */ + public TableFactory(MySQLConnection connection) { + this.connection = connection; + } + + /** + * Registers and creates a sql table + * + * @param table The table you want to register + * @return this class + */ + public TableFactory register(SQLTable table) { + table.create(); + REGISTERED_TABLES.put(table.getClass(), table); + return this; + } + + /** + * Gets a registered table from the list + * + * @param tableClass The class of the table you want to get + * @return the instance of the table + */ + public SQLTable getTable(Class tableClass) { + return REGISTERED_TABLES.get(tableClass); + } + + /** + * Gets a storage medium from the list + * + * @param storageClass The class of the storage medium you want to get + * @return the storage medium + */ + public SQLStorageMedium getStorage(Class storageClass) { + return (SQLStorageMedium) getTable(storageClass); + } + +} diff --git a/src/main/java/de/gnmyt/sqltoolkit/generator/TableGenerator.java b/src/main/java/de/gnmyt/sqltoolkit/generator/TableGenerator.java new file mode 100644 index 0000000..c7c1c7d --- /dev/null +++ b/src/main/java/de/gnmyt/sqltoolkit/generator/TableGenerator.java @@ -0,0 +1,91 @@ +package de.gnmyt.sqltoolkit.generator; + +import de.gnmyt.sqltoolkit.drivers.MySQLConnection; +import de.gnmyt.sqltoolkit.queries.TableCreationQuery; +import de.gnmyt.sqltoolkit.querybuilder.QueryParameter; +import de.gnmyt.sqltoolkit.querybuilder.SQLQuery; +import de.gnmyt.sqltoolkit.types.SQLType; +import de.gnmyt.sqltoolkit.types.TableField; + +import java.util.ArrayList; + +public class TableGenerator { + + private final MySQLConnection connection; + + private final ArrayList fields = new ArrayList<>(); + private final String tableName; + + /** + * Basic constructor for the {@link TableGenerator} + * + * @param tableName Name of the table + */ + public TableGenerator(MySQLConnection connection, String tableName) { + this.tableName = tableName; + this.connection = connection; + addField(SQLType.INTEGER, "id", 255, null, "AUTO_INCREMENT"); + } + + /** + * Add a field to the Table + * + * @param type The type of the field you want to add + * @param name The name of the field you want to add + * @param length The length of the field you want to add + * @param defaultValue The default value of the field (leave empty for no default value) + * @param extras Optional parameters you want to add to the statement + * @return this class + */ + public TableGenerator addField(SQLType type, String name, Integer length, String defaultValue, String... extras) { + fields.add(new TableField().setType(type).setName(name).setLength(length).setDefaultValue(defaultValue).setExtras(extras)); + return this; + } + + /** + * Add a field to the Table + * + * @param type The type of the field you want to add + * @param name The name of the field you want to add + * @param length The length of the field you want to add + * @return this class + */ + public TableGenerator addField(SQLType type, String name, Integer length) { + return addField(type, name, length, ""); + } + + /** + * Add a field to the table + * + * @param field The field you want to add + * @return this class + */ + public TableGenerator addField(TableField field) { + fields.add(field); + return this; + } + + /** + * Add a field to the Table + * + * @param type The type of the field you want to add + * @param name The name of the field you want to add + * @return this class + */ + public TableGenerator addField(SQLType type, String name) { + return addField(type, name, 255, ""); + } + + /** + * Creates the table you wanted + */ + public void create() { + SQLQuery query = connection.createQuery(TableCreationQuery.class) + .addParameter(QueryParameter.TABLE_NAME, tableName) + .addParameter(QueryParameter.FIELD_LIST, fields) + .addParameter(QueryParameter.PRIMARY_KEY, "id") + .build(); + connection.update(query); + } + +} diff --git a/src/main/java/de/gnmyt/sqltoolkit/manager/ConnectSettingsManager.java b/src/main/java/de/gnmyt/sqltoolkit/manager/ConnectSettingsManager.java new file mode 100644 index 0000000..4a1693d --- /dev/null +++ b/src/main/java/de/gnmyt/sqltoolkit/manager/ConnectSettingsManager.java @@ -0,0 +1,249 @@ +package de.gnmyt.sqltoolkit.manager; + +import de.gnmyt.sqltoolkit.drivers.MySQLConnection; + +import java.nio.charset.StandardCharsets; +import java.util.HashMap; + +public class ConnectSettingsManager { + + private final MySQLConnection connection; + + private final HashMap settingValues = new HashMap<>(); + + public ConnectSettingsManager(MySQLConnection connection) { + this.connection = connection; + } + + /** + * Adds a custom property to the values + * + * @param property The property you want to add + * @param value The value you want to use + * @return this class + */ + public ConnectSettingsManager customProperty(String property, Object value) { + settingValues.put(property, value); + return this; + } + + /** + * Sets the timezone of the connection + * + * @param timezone The new timezone + * @return this class + */ + public ConnectSettingsManager timezone(String timezone) { + settingValues.put("useTimezone", true); + settingValues.put("serverTimezone", timezone); + return this; + } + + /** + * Sets the requireSSL property + * + * @param requireSSL The new value of the requireSSL property + * @return this class + */ + public ConnectSettingsManager requireSSL(boolean requireSSL) { + settingValues.put("requireSSL", requireSSL); + return this; + } + + /** + * Sets the useSSL property + * + * @param useSSL The new value of the useSSL property + * @return this class + */ + public ConnectSettingsManager useSSL(boolean useSSL) { + settingValues.put("useSSL", useSSL); + return this; + } + + /** + * Sets the autoReconnect property + * + * @param autoReconnect The new value of the autoReconnect property + * @return this class + */ + public ConnectSettingsManager autoReconnect(boolean autoReconnect) { + settingValues.put("autoReconnect", autoReconnect); + return this; + } + + /** + * Sets the maxReconnects property + * + * @param maxReconnects The new value of the maxReconnects property + * @return this class + */ + public ConnectSettingsManager maxReconnects(int maxReconnects) { + settingValues.put("maxReconnects", maxReconnects); + return this; + } + + /** + * Sets the charset property + * + * @param charset The new value of the charset property + * @return this class + */ + public ConnectSettingsManager characterEncoding(StandardCharsets charset) { + settingValues.put("characterEncoding", charset.toString()); + return this; + } + + /** + * Sets the connectTimeout property + * + * @param connectTimeout The new value of the connectTimeout property + * @return this class + */ + public ConnectSettingsManager connectTimeout(int connectTimeout) { + settingValues.put("connectTimeout", connectTimeout); + return this; + } + + /** + * Sets the socketTimeout property + * + * @param socketTimeout The new value of the socketTimeout property + * @return this class + */ + public ConnectSettingsManager socketTimeout(int socketTimeout) { + settingValues.put("socketTimeout", socketTimeout); + return this; + } + + /** + * Sets the tcpKeepAlive property + * + * @param tcpKeepAlive The new value of the tcpKeepAlive property + * @return this class + */ + public ConnectSettingsManager tcpKeepAlive(boolean tcpKeepAlive) { + settingValues.put("tcpKeepAlive", tcpKeepAlive); + return this; + } + + /** + * Sets the tcpNoDelay property + * + * @param tcpNoDelay The new value of the tcpNoDelay property + * @return this class + */ + public ConnectSettingsManager tcpNoDelay(boolean tcpNoDelay) { + settingValues.put("tcpNoDelay", tcpNoDelay); + return this; + } + + /** + * Sets the tcpRcvBuf property + * + * @param tcpRcvBuf The new value of the tcpRcvBuf property + * @return this class + */ + public ConnectSettingsManager tcpRcvBuf(int tcpRcvBuf) { + settingValues.put("tcpRcvBuf", tcpRcvBuf); + return this; + } + + /** + * Sets the tcpSndBuf property + * + * @param tcpSndBuf The new value of the tcpSndBuf property + * @return this class + */ + public ConnectSettingsManager tcpSndBuf(int tcpSndBuf) { + settingValues.put("tcpSndBuf", tcpSndBuf); + return this; + } + + /** + * Sets the maxAllowedPacket property + * + * @param maxAllowedPacket The new value of the maxAllowedPacket property + * @return this class + */ + public ConnectSettingsManager maxAllowedPacket(int maxAllowedPacket) { + settingValues.put("maxAllowedPacket", maxAllowedPacket); + return this; + } + + /** + * Sets the tcpTrafficClass property + * + * @param tcpTrafficClass The new value of the tcpTrafficClass property + * @return this class + */ + public ConnectSettingsManager tcpTrafficClass(int tcpTrafficClass) { + settingValues.put("tcpTrafficClass", tcpTrafficClass); + return this; + } + + /** + * Sets the useCompression property + * + * @param useCompression The new value of the useCompression property + * @return this class + */ + public ConnectSettingsManager useCompression(boolean useCompression) { + settingValues.put("useCompression", useCompression); + return this; + } + + /** + * Sets the useUnbufferedInput property + * + * @param useUnbufferedInput The new value of the useUnbufferedInput property + * @return this class + */ + public ConnectSettingsManager useUnbufferedInput(boolean useUnbufferedInput) { + settingValues.put("useUnbufferedInput", useUnbufferedInput); + return this; + } + + /** + * Sets the paranoid property + * + * @param paranoid The new value of the paranoid property + * @return this class + */ + public ConnectSettingsManager paranoid(boolean paranoid) { + settingValues.put("paranoid", paranoid); + return this; + } + + /** + * Sets the verifyServerCertificate property + * + * @param verifyServerCertificate The new value of the verifyServerCertificate property + * @return this class + */ + public ConnectSettingsManager verifyServerCertificate(boolean verifyServerCertificate) { + settingValues.put("verifyServerCertificate", verifyServerCertificate); + return this; + } + + /** + * Creates the connection string + * + * @return the connection string + */ + public String generateConnectionString() { + StringBuilder builder = new StringBuilder(); + + Object[] keys = settingValues.keySet().toArray(); + Object[] values = settingValues.values().toArray(); + + for (int i = 0; i < settingValues.size(); i++) { + if (i == 0) builder.append("?"); + else builder.append("&"); + + builder.append(keys[i]).append("=").append(values[i]); + } + return builder.toString(); + } + +} diff --git a/src/main/java/de/gnmyt/sqltoolkit/manager/CustomTableFieldManager.java b/src/main/java/de/gnmyt/sqltoolkit/manager/CustomTableFieldManager.java new file mode 100644 index 0000000..66a6464 --- /dev/null +++ b/src/main/java/de/gnmyt/sqltoolkit/manager/CustomTableFieldManager.java @@ -0,0 +1,106 @@ +package de.gnmyt.sqltoolkit.manager; + +import de.gnmyt.sqltoolkit.storage.SQLTable; +import de.gnmyt.sqltoolkit.types.SQLType; +import de.gnmyt.sqltoolkit.types.TableField; + +public class CustomTableFieldManager { + + private final SQLTable table; + + private final TableField field = new TableField(); + + /** + * Basic constructor of the {@link CustomTableFieldManager} + * + * @param table Your current sql table + */ + public CustomTableFieldManager(SQLTable table) { + this.table = table; + } + + /** + * Set the name of the table field + * + * @param name The new name of the table field + * @return this class + */ + public CustomTableFieldManager name(String name) { + field.setName(name); + return this; + } + + /** + * Sets the type of the table field + * + * @param type The new type of the table field + * @return this class + */ + public CustomTableFieldManager type(SQLType type) { + field.setType(type.getValue()); + return this; + } + + /** + * Sets the type of the table field as a string + * + * @param type The new type of the table field + * @return this class + */ + public CustomTableFieldManager type(String type) { + field.setType(type); + return this; + } + + /** + * Sets the length of the table field + * + * @param length The new length of the table field + * @return this class + */ + public CustomTableFieldManager length(int length) { + field.setLength(length); + return this; + } + + /** + * Allows a null in the table field + * + * @param allowNull true if a NULL is allowed, otherwise false + * @return this class + */ + public CustomTableFieldManager allowNull(boolean allowNull) { + field.setAllowNull(allowNull); + return this; + } + + /** + * Sets the default value of the table field + * + * @param defaultValue The new default value of the table field + * @return this class + */ + public CustomTableFieldManager defaultValue(String defaultValue) { + field.setDefaultValue(defaultValue); + return this; + } + + /** + * Sets the extras of the table field + * + * @param extras The new extras of the table field + * @return this class + */ + public CustomTableFieldManager extras(String[] extras) { + field.setExtras(extras); + return this; + } + + /** + * Adds the current field to the sql table + */ + public void add() { + table.custom(field); + } + +} diff --git a/src/main/java/de/gnmyt/sqltoolkit/manager/DeletionManager.java b/src/main/java/de/gnmyt/sqltoolkit/manager/DeletionManager.java new file mode 100644 index 0000000..bcaeea6 --- /dev/null +++ b/src/main/java/de/gnmyt/sqltoolkit/manager/DeletionManager.java @@ -0,0 +1,81 @@ +package de.gnmyt.sqltoolkit.manager; + +import de.gnmyt.sqltoolkit.drivers.MySQLConnection; +import de.gnmyt.sqltoolkit.queries.DeletionQuery; +import de.gnmyt.sqltoolkit.querybuilder.QueryParameter; +import de.gnmyt.sqltoolkit.querybuilder.SQLQuery; +import org.slf4j.Logger; + +import java.util.HashMap; + +public class DeletionManager { + + private final Logger LOG = MySQLConnection.LOG; + + private final MySQLConnection connection; + + private final HashMap whereList = new HashMap<>(); + private String tableName; + + /** + * Advanced constructor for the {@link DeletionManager} + * + * @param connection The current connection + * @param tableName The table name + */ + public DeletionManager(MySQLConnection connection, String tableName) { + this.connection = connection; + this.tableName = tableName; + } + + /** + * Basic constructor for the {@link DeletionManager} + * + * @param connection The current connection + */ + public DeletionManager(MySQLConnection connection) { + this.connection = connection; + } + + /** + * Sets the table name + * + * @param tableName The table name + * @return this class + */ + public DeletionManager from(String tableName) { + this.tableName = tableName; + return this; + } + + /** + * Adding another 'where'-statement + * + * @param column Table column name + * @param value Table value name + * @return this class + */ + public DeletionManager where(String column, Object value) { + whereList.put(column, value); + return this; + } + + /** + * Executes the 'delete'-statement + */ + public void execute() { + connection.update(build()); + } + + /** + * Builds the current statement + * + * @return the current statement + */ + private SQLQuery build() { + return connection.createQuery(DeletionQuery.class) + .addParameter(QueryParameter.TABLE_NAME, tableName) + .addParameter(QueryParameter.WHERE_LIST, whereList).build(); + } + +} diff --git a/src/main/java/de/gnmyt/sqltoolkit/manager/InsertManager.java b/src/main/java/de/gnmyt/sqltoolkit/manager/InsertManager.java new file mode 100644 index 0000000..0078bf7 --- /dev/null +++ b/src/main/java/de/gnmyt/sqltoolkit/manager/InsertManager.java @@ -0,0 +1,78 @@ +package de.gnmyt.sqltoolkit.manager; + +import de.gnmyt.sqltoolkit.drivers.MySQLConnection; +import de.gnmyt.sqltoolkit.queries.InsertQuery; +import de.gnmyt.sqltoolkit.querybuilder.QueryParameter; +import de.gnmyt.sqltoolkit.querybuilder.SQLQuery; + +import java.util.HashMap; + +public class InsertManager { + + private final MySQLConnection connection; + private final HashMap values; + private String tableName; + + /** + * Basic constructor for the InsertManager + * + * @param connection The current connection + */ + public InsertManager(MySQLConnection connection) { + this.connection = connection; + values = new HashMap<>(); + } + + /** + * Constructor with direct tableName integration + * + * @param connection The current connection + * @param tableName The name of the table + */ + public InsertManager(MySQLConnection connection, String tableName) { + this.connection = connection; + this.tableName = tableName; + values = new HashMap<>(); + } + + /** + * Optionally add the tableName / Change the name of the table + * + * @param tableName The name of the table + */ + public void to(String tableName) { + this.tableName = tableName; + } + + /** + * Query value + * + * @param fieldName The name of the column + * @param value The value of the object you want to insert + * @return this class + */ + public InsertManager value(String fieldName, Object value) { + values.put(fieldName, value); + return this; + } + + /** + * Executes the current SQL query + */ + public void execute() { + connection.update(build()); + } + + /** + * Builds the current statement + * + * @return the current statement + */ + private SQLQuery build() { + return connection.createQuery(InsertQuery.class) + .addParameter(QueryParameter.TABLE_NAME, tableName) + .addParameter(QueryParameter.VALUE_LIST, values) + .build(); + } + +} diff --git a/src/main/java/de/gnmyt/SQLToolkit/manager/ResultManager.java b/src/main/java/de/gnmyt/sqltoolkit/manager/ResultManager.java similarity index 50% rename from src/main/java/de/gnmyt/SQLToolkit/manager/ResultManager.java rename to src/main/java/de/gnmyt/sqltoolkit/manager/ResultManager.java index d4d1fb5..1b66e11 100644 --- a/src/main/java/de/gnmyt/SQLToolkit/manager/ResultManager.java +++ b/src/main/java/de/gnmyt/sqltoolkit/manager/ResultManager.java @@ -1,34 +1,31 @@ -package de.gnmyt.SQLToolkit.manager; +package de.gnmyt.sqltoolkit.manager; -import de.gnmyt.SQLToolkit.drivers.SqlLogManager; +import de.gnmyt.sqltoolkit.drivers.MySQLConnection; +import org.slf4j.Logger; import java.sql.ResultSet; import java.sql.Timestamp; import java.util.ArrayList; import java.util.HashMap; -/******************************** - * @author Mathias Wagner - * Created 23.12.2020 - ********************************/ - public class ResultManager { - private ResultSet resultSet; - private SqlLogManager logManager; + private final Logger LOG = MySQLConnection.LOG; + + private final ResultSet resultSet; /** * Basic constructor for the ResultManager + * * @param resultSet Existing ResultSet - * @param logManager Existing LogManager */ - public ResultManager(ResultSet resultSet, SqlLogManager logManager) { + public ResultManager(ResultSet resultSet) { this.resultSet = resultSet; - this.logManager = logManager; } /** * Getting the ResultSet + * * @return ResultSet */ public ResultSet getResultSet() { @@ -37,92 +34,149 @@ public class ResultManager { /** * 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()); } + try { + while (resultSet.next()) { + return resultSet.getObject(column); + } + } catch (Exception err) { + LOG.error(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()); } + try { + while (resultSet.next()) { + return resultSet.getString(column); + } + } catch (Exception err) { + LOG.error(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()); } + try { + while (resultSet.next()) { + return resultSet.getInt(column); + } + } catch (Exception err) { + LOG.error(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()); } + try { + while (resultSet.next()) { + return resultSet.getBoolean(column); + } + } catch (Exception err) { + LOG.error(err.getMessage()); + } return false; } public Timestamp getTimestamp(String column) { - try { while (resultSet.next()) { return resultSet.getTimestamp(column); } - } catch (Exception err) { logManager.sendError(err.getMessage()); } + try { + while (resultSet.next()) { + return resultSet.getTimestamp(column); + } + } catch (Exception err) { + LOG.error(err.getMessage()); + } return null; } /** * 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()); } + int count = 0; + try { + while (resultSet.next()) { + count++; + } + } catch (Exception err) { + LOG.error(err.getMessage()); + } return count; } + /** + * Checks if the current result exists + * + * @return true if the current result exists, otherwise false + */ + public boolean exists() { + return getRowCount() != 0; + } + /** * 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()); } + try { + while (resultSet.next()) { + results.add(resultSet.getString(column)); + } + } catch (Exception err) { + LOG.error(err.getMessage()); + } return results; } /** * Get a List of all Results for 2 columns - * @param column Table column #1 + * + * @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()); } + try { + while (resultSet.next()) { + results.put(resultSet.getString(column), resultSet.getString(column2)); + } + } catch (Exception err) { + LOG.error(err.getMessage()); + } return results; } /** * Get a list of all results with all columns + * * @return ArrayList with the result */ public ArrayList> getList() { @@ -130,13 +184,15 @@ public class ResultManager { try { while (resultSet.next()) { HashMap result = new HashMap<>(); - for (int i=0; i < resultSet.getMetaData().getColumnCount(); i++) { - String columnName = resultSet.getMetaData().getColumnName(i+1); + for (int i = 0; i < resultSet.getMetaData().getColumnCount(); i++) { + String columnName = resultSet.getMetaData().getColumnName(i + 1); result.put(columnName, resultSet.getObject(columnName)); } results.add(result); } - } catch (Exception err) { logManager.sendError(err.getMessage()); } + } catch (Exception err) { + LOG.error(err.getMessage()); + } return results; } diff --git a/src/main/java/de/gnmyt/sqltoolkit/manager/SelectionManager.java b/src/main/java/de/gnmyt/sqltoolkit/manager/SelectionManager.java new file mode 100644 index 0000000..9aac725 --- /dev/null +++ b/src/main/java/de/gnmyt/sqltoolkit/manager/SelectionManager.java @@ -0,0 +1,131 @@ +package de.gnmyt.sqltoolkit.manager; + +import de.gnmyt.sqltoolkit.drivers.MySQLConnection; +import de.gnmyt.sqltoolkit.queries.SelectionQuery; +import de.gnmyt.sqltoolkit.querybuilder.QueryBuilder; +import de.gnmyt.sqltoolkit.querybuilder.QueryParameter; +import de.gnmyt.sqltoolkit.querybuilder.SQLQuery; +import org.slf4j.Logger; + +import java.sql.ResultSet; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; + +public class SelectionManager { + + private final Logger LOG = MySQLConnection.LOG; + private final MySQLConnection connection; + + private final HashMap WHERE_LIST = new HashMap<>(); + private final ArrayList SELECTION_LIST = new ArrayList<>(); + + private String limit = ""; + private String tableName = "default"; + + /** + * Advanced constructor of the {@link SelectionManager} with a prefilled table name + * + * @param connection The current connection + * @param tableName The table name + */ + public SelectionManager(MySQLConnection connection, String tableName) { + this.connection = connection; + this.tableName = tableName; + } + + /** + * Basic constructor of the {@link SelectionManager} + * + * @param connection The current connection + */ + public SelectionManager(MySQLConnection connection) { + this.connection = connection; + } + + public SelectionManager select(String... selection) { + SELECTION_LIST.addAll(Arrays.asList(selection)); + return this; + } + + /** + * Sets the table name of the selection + * + * @param tableName The new table name + * @return this class + */ + public SelectionManager from(String tableName) { + this.tableName = tableName; + return this; + } + + /** + * Adding another 'where'-statement + * + * @param column Table column name + * @param value Table value name + * @return this class + */ + public SelectionManager where(String column, Object value) { + WHERE_LIST.put(column, value); + return this; + } + + /** + * Sets the limit of the rows + * + * @param limit The new limit + * @return this class + */ + public SelectionManager limit(int limit) { + this.limit = String.valueOf(limit); + return this; + } + + /** + * Sets the limit of the rows + * + * @param startRow The first row that should be counted + * @param limit The new limit + * @return this class + */ + public SelectionManager limit(int startRow, int limit) { + this.limit = startRow + "," + limit; + return this; + } + + /** + * Get the ResultManager + * + * @return ResultManager + */ + public ResultManager getResult() { + return connection.getResult(build()); + } + + /** + * Get the ResultSet + * + * @return ResultSet + */ + public ResultSet getResultSet() { + return connection.getResultSet(build()); + } + + /** + * Builds the query + * + * @return the built query + */ + private SQLQuery build() { + QueryBuilder query = connection.createQuery(SelectionQuery.class) + .addParameter(QueryParameter.TABLE_NAME, tableName) + .addParameter(QueryParameter.LIMIT, limit) + .addParameter(QueryParameter.WHERE_LIST, WHERE_LIST); + + if (!SELECTION_LIST.isEmpty()) query.addParameter(QueryParameter.SELECT_LIST, SELECTION_LIST); + + return query.build(); + } + +} diff --git a/src/main/java/de/gnmyt/sqltoolkit/manager/UpdateManager.java b/src/main/java/de/gnmyt/sqltoolkit/manager/UpdateManager.java new file mode 100644 index 0000000..3827f0f --- /dev/null +++ b/src/main/java/de/gnmyt/sqltoolkit/manager/UpdateManager.java @@ -0,0 +1,99 @@ +package de.gnmyt.sqltoolkit.manager; + +import de.gnmyt.sqltoolkit.drivers.MySQLConnection; +import de.gnmyt.sqltoolkit.queries.UpdateQuery; +import de.gnmyt.sqltoolkit.querybuilder.QueryParameter; +import de.gnmyt.sqltoolkit.querybuilder.SQLQuery; +import org.slf4j.Logger; + +import java.util.HashMap; + +public class UpdateManager { + + private final Logger LOG = MySQLConnection.LOG; + + private final MySQLConnection connection; + private final HashMap whereList; + private final HashMap setList; + private String tableName; + + /** + * 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; + this.tableName = tableName; + this.whereList = new HashMap<>(); + this.setList = new HashMap<>(); + } + + /** + * Change the tableName + * + * @param tableName New tableName + * @return this class + */ + public UpdateManager toTable(String tableName) { + this.tableName = 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; + } + + /** + * Update the entries with your current conditions + */ + public void execute() { + connection.update(build()); + } + + /** + * Builds the current statement + * + * @return the current statement + */ + private SQLQuery build() { + return connection.createQuery(UpdateQuery.class) + .addParameter(QueryParameter.TABLE_NAME, tableName) + .addParameter(QueryParameter.WHERE_LIST, whereList) + .addParameter(QueryParameter.SET_LIST, setList) + .build(); + } + +} diff --git a/src/main/java/de/gnmyt/sqltoolkit/queries/DeletionQuery.java b/src/main/java/de/gnmyt/sqltoolkit/queries/DeletionQuery.java new file mode 100644 index 0000000..ed718bd --- /dev/null +++ b/src/main/java/de/gnmyt/sqltoolkit/queries/DeletionQuery.java @@ -0,0 +1,61 @@ +package de.gnmyt.sqltoolkit.queries; + +import de.gnmyt.sqltoolkit.querybuilder.AbstractQuery; +import de.gnmyt.sqltoolkit.querybuilder.SQLQuery; +import de.gnmyt.sqltoolkit.querybuilder.StatementBuilder; + +import java.util.HashMap; + +import static de.gnmyt.sqltoolkit.querybuilder.QueryParameter.TABLE_NAME; +import static de.gnmyt.sqltoolkit.querybuilder.QueryParameter.WHERE_LIST; + +public class DeletionQuery extends AbstractQuery { + + @Override + public void defaults() { + addParameter(WHERE_LIST, new HashMap()); + addParameter(TABLE_NAME, "default"); + } + + /** + * Builds the 'where'-list + * + * @return the 'where'-list as a string + */ + public String buildWhereList() { + StatementBuilder whereString = new StatementBuilder(); + + HashMap whereList = (HashMap) getParameter(WHERE_LIST); + + for (int i = 0; i < whereList.size(); i++) { + if (i == 0) whereString.append("WHERE"); + else whereString.append("AND"); + + whereString.append("`" + whereList.keySet().toArray()[i] + "`").append("=").append("?"); + } + + return whereString.toString(); + } + + /** + * Gets the parameters + * + * @return the parameters + */ + public Object[] getParameters() { + + HashMap whereList = (HashMap) getParameter(WHERE_LIST); + + return whereList.values().toArray(); + } + + @Override + public SQLQuery build() { + + StatementBuilder builder = new StatementBuilder("DELETE").append("FROM").append("`" + getParameter(TABLE_NAME) + "`"); + + builder.append(buildWhereList()); + + return new SQLQuery().setStatement(builder.toString()).setParameters(getParameters()); + } +} diff --git a/src/main/java/de/gnmyt/sqltoolkit/queries/InsertQuery.java b/src/main/java/de/gnmyt/sqltoolkit/queries/InsertQuery.java new file mode 100644 index 0000000..4c45649 --- /dev/null +++ b/src/main/java/de/gnmyt/sqltoolkit/queries/InsertQuery.java @@ -0,0 +1,82 @@ +package de.gnmyt.sqltoolkit.queries; + +import de.gnmyt.sqltoolkit.querybuilder.AbstractQuery; +import de.gnmyt.sqltoolkit.querybuilder.SQLQuery; +import de.gnmyt.sqltoolkit.querybuilder.StatementBuilder; + +import java.util.HashMap; + +import static de.gnmyt.sqltoolkit.querybuilder.QueryParameter.TABLE_NAME; +import static de.gnmyt.sqltoolkit.querybuilder.QueryParameter.VALUE_LIST; + +public class InsertQuery extends AbstractQuery { + + @Override + public void defaults() { + addParameter(TABLE_NAME, "default"); + addParameter(VALUE_LIST, new HashMap()); + } + + /** + * Builds the rows of the 'values'-list + * + * @return the rows of the 'values'-list as a string + */ + public String buildRowList() { + StatementBuilder rowString = new StatementBuilder("("); + + HashMap valueList = (HashMap) getParameter(VALUE_LIST); + + for (int i = 0; i < valueList.size(); i++) { + if (i > 0) rowString.appendDefault(","); + rowString.append("`").appendDefault(valueList.keySet().toArray()[i].toString()).appendDefault("`"); + } + + return rowString.append(")").build(); + } + + /** + * Builds the 'values'-list + * + * @return the 'values'-list as a string + */ + public String buildValueList() { + StatementBuilder valueString = new StatementBuilder(); + + HashMap valueList = (HashMap) getParameter(VALUE_LIST); + + valueString.append(valueList.size() > 0 ? "VALUES (" : ""); + + for (int i = 0; i < valueList.size(); i++) { + if (i > 0) valueString.appendDefault(","); + valueString.append("?"); + } + + if (valueList.size() > 0) valueString.append(")"); + + return valueString.toString(); + } + + /** + * Gets the parameters + * + * @return the parameters + */ + public Object[] getParameters() { + + HashMap valueList = (HashMap) getParameter(VALUE_LIST); + + return valueList.values().toArray(); + } + + @Override + public SQLQuery build() { + StatementBuilder builder = new StatementBuilder("INSERT INTO").append("`" + getParameter(TABLE_NAME) + "`"); + + builder.append(buildRowList()); + + builder.append(buildValueList()); + + return new SQLQuery().setStatement(builder.build()).setParameters(getParameters()); + } +} diff --git a/src/main/java/de/gnmyt/sqltoolkit/queries/SelectionQuery.java b/src/main/java/de/gnmyt/sqltoolkit/queries/SelectionQuery.java new file mode 100644 index 0000000..027bce5 --- /dev/null +++ b/src/main/java/de/gnmyt/sqltoolkit/queries/SelectionQuery.java @@ -0,0 +1,85 @@ +package de.gnmyt.sqltoolkit.queries; + +import de.gnmyt.sqltoolkit.querybuilder.AbstractQuery; +import de.gnmyt.sqltoolkit.querybuilder.SQLQuery; +import de.gnmyt.sqltoolkit.querybuilder.StatementBuilder; + +import java.util.ArrayList; +import java.util.HashMap; + +import static de.gnmyt.sqltoolkit.querybuilder.QueryParameter.*; + +public class SelectionQuery extends AbstractQuery { + + @Override + public void defaults() { + + ArrayList selectList = new ArrayList<>(); + selectList.add("*"); + + addParameter(SELECT_LIST, selectList); + addParameter(WHERE_LIST, new HashMap()); + addParameter(TABLE_NAME, "default"); + } + + /** + * Builds the selection list + * + * @return the list as a string + */ + public String buildSelectionList() { + StringBuilder selectionString = new StringBuilder(); + + for (String selectItem : ((ArrayList) getParameter(SELECT_LIST))) { + if (!selectionString.toString().isEmpty()) selectionString.append(", "); + selectionString.append(selectItem); + } + + return selectionString.toString(); + } + + /** + * Builds the 'where'-list + * + * @return the 'where'-list as a string + */ + public String buildWhereList() { + StatementBuilder whereString = new StatementBuilder(); + + HashMap whereList = (HashMap) getParameter(WHERE_LIST); + + for (int i = 0; i < whereList.size(); i++) { + if (i == 0) whereString.append("WHERE"); + else whereString.append("AND"); + + whereString.append("`" + whereList.keySet().toArray()[i] + "`").append("=").append("?"); + } + + return whereString.toString(); + } + + /** + * Gets the parameters + * + * @return the parameters + */ + public Object[] getParameters() { + + HashMap whereList = (HashMap) getParameter(WHERE_LIST); + + return whereList.values().toArray(); + } + + @Override + public SQLQuery build() { + + StatementBuilder builder = new StatementBuilder("SELECT").append(buildSelectionList()).append("FROM").append("`" + getParameter(TABLE_NAME) + "`"); + + builder.append(buildWhereList()); + + if (getParameter(LIMIT) != null) builder.append("LIMIT").append(getParameter(LIMIT).toString()); + + return new SQLQuery().setStatement(builder.build()).setParameters(getParameters()); + } + +} diff --git a/src/main/java/de/gnmyt/sqltoolkit/queries/TableCreationQuery.java b/src/main/java/de/gnmyt/sqltoolkit/queries/TableCreationQuery.java new file mode 100644 index 0000000..2eec247 --- /dev/null +++ b/src/main/java/de/gnmyt/sqltoolkit/queries/TableCreationQuery.java @@ -0,0 +1,51 @@ +package de.gnmyt.sqltoolkit.queries; + +import de.gnmyt.sqltoolkit.querybuilder.AbstractQuery; +import de.gnmyt.sqltoolkit.querybuilder.QueryParameter; +import de.gnmyt.sqltoolkit.querybuilder.SQLQuery; +import de.gnmyt.sqltoolkit.querybuilder.StatementBuilder; +import de.gnmyt.sqltoolkit.types.TableField; + +import java.util.ArrayList; + +import static de.gnmyt.sqltoolkit.querybuilder.QueryParameter.PRIMARY_KEY; + +public class TableCreationQuery extends AbstractQuery { + + @Override + public void defaults() { + addParameter(QueryParameter.TABLE_NAME, "default"); + addParameter(QueryParameter.FIELD_LIST, new ArrayList()); + addParameter(PRIMARY_KEY, ""); + } + + /** + * Builds the field list + * + * @return the field list as a string + */ + public String buildFieldList() { + StatementBuilder builder = new StatementBuilder("("); + + ArrayList fieldList = (ArrayList) getParameter(QueryParameter.FIELD_LIST); + + for (int i = 0; i < fieldList.size(); i++) { + if (i > 0) builder.appendDefault(","); + builder.append(fieldList.get(i).generateSQLRow()); + } + + if (!((String) getParameter(PRIMARY_KEY)).isEmpty()) + builder.appendDefault(String.format(", PRIMARY KEY (%s)", getParameter(PRIMARY_KEY))); + + return builder.append(")").build(); + } + + @Override + public SQLQuery build() { + StatementBuilder builder = new StatementBuilder("CREATE TABLE IF NOT EXISTS").append("`" + getParameter(QueryParameter.TABLE_NAME) + "`"); + + builder.append(buildFieldList()); + + return new SQLQuery().setStatement(builder.build()); + } +} diff --git a/src/main/java/de/gnmyt/sqltoolkit/queries/UpdateQuery.java b/src/main/java/de/gnmyt/sqltoolkit/queries/UpdateQuery.java new file mode 100644 index 0000000..f17aa3e --- /dev/null +++ b/src/main/java/de/gnmyt/sqltoolkit/queries/UpdateQuery.java @@ -0,0 +1,82 @@ +package de.gnmyt.sqltoolkit.queries; + +import de.gnmyt.sqltoolkit.querybuilder.AbstractQuery; +import de.gnmyt.sqltoolkit.querybuilder.SQLQuery; +import de.gnmyt.sqltoolkit.querybuilder.StatementBuilder; + +import java.util.ArrayList; +import java.util.HashMap; + +import static de.gnmyt.sqltoolkit.querybuilder.QueryParameter.*; + +public class UpdateQuery extends AbstractQuery { + + @Override + public void defaults() { + addParameter(TABLE_NAME, "default"); + addParameter(WHERE_LIST, new HashMap()); + addParameter(SET_LIST, new HashMap()); + } + + /** + * Builds the 'set'-list + * + * @return the 'set'-list as a string + */ + public String buildSetList() { + StatementBuilder builder = new StatementBuilder("SET"); + + HashMap setList = (HashMap) getParameter(SET_LIST); + + for (int i = 0; i < setList.size(); i++) { + if (i > 0) builder.appendDefault(","); + builder.append("`" + setList.keySet().toArray()[i] + "`").append("=").append("?"); + } + + return builder.build(); + } + + /** + * Builds the 'where'-list + * + * @return the 'where'-list as a string + */ + public String buildWhereList() { + StatementBuilder builder = new StatementBuilder("WHERE"); + + HashMap whereList = (HashMap) getParameter(WHERE_LIST); + + for (int i = 0; i < whereList.size(); i++) { + if (i > 0) builder.append("AND"); + builder.append("`" + whereList.keySet().toArray()[i] + "`").append("=").append("?"); + } + + return builder.build(); + } + + /** + * Gets the parameters + * + * @return the parameters + */ + public Object[] getParameters() { + + ArrayList tempParameters = new ArrayList<>(); + + ((HashMap) getParameter(SET_LIST)).forEach((str, obj) -> tempParameters.add(obj)); + ((HashMap) getParameter(WHERE_LIST)).forEach((str, obj) -> tempParameters.add(obj)); + + return tempParameters.toArray(); + } + + @Override + public SQLQuery build() { + StatementBuilder builder = new StatementBuilder("UPDATE").append("`" + getParameter(TABLE_NAME) + "`"); + + if (!((HashMap) getParameter(SET_LIST)).isEmpty()) builder.append(buildSetList()); + + if (!((HashMap) getParameter(WHERE_LIST)).isEmpty()) builder.append(buildWhereList()); + + return new SQLQuery().setStatement(builder.build()).setParameters(getParameters()); + } +} diff --git a/src/main/java/de/gnmyt/sqltoolkit/querybuilder/AbstractQuery.java b/src/main/java/de/gnmyt/sqltoolkit/querybuilder/AbstractQuery.java new file mode 100644 index 0000000..b4dcaf0 --- /dev/null +++ b/src/main/java/de/gnmyt/sqltoolkit/querybuilder/AbstractQuery.java @@ -0,0 +1,41 @@ +package de.gnmyt.sqltoolkit.querybuilder; + +import java.util.HashMap; + +public abstract class AbstractQuery { + + private final HashMap PARAMETERS = new HashMap<>(); + + /** + * Here the query adds its default values + */ + public abstract void defaults(); + + /** + * The building logic of the sql query + * + * @return the sql query + */ + public abstract SQLQuery build(); + + /** + * Adds a query parameter to the building list + * + * @param type The type you want to use + * @param value The value of the type + */ + public void addParameter(QueryParameter type, Object value) { + PARAMETERS.put(type, value); + } + + /** + * Gets a query parameter from the building list + * + * @param type The type you want to get + * @return the query parameter + */ + protected Object getParameter(QueryParameter type) { + return PARAMETERS.get(type); + } + +} diff --git a/src/main/java/de/gnmyt/sqltoolkit/querybuilder/QueryBuilder.java b/src/main/java/de/gnmyt/sqltoolkit/querybuilder/QueryBuilder.java new file mode 100644 index 0000000..d010c28 --- /dev/null +++ b/src/main/java/de/gnmyt/sqltoolkit/querybuilder/QueryBuilder.java @@ -0,0 +1,48 @@ +package de.gnmyt.sqltoolkit.querybuilder; + +import de.gnmyt.sqltoolkit.drivers.MySQLConnection; +import org.slf4j.Logger; + +public class QueryBuilder { + + private static final Logger LOG = MySQLConnection.LOG; + + private AbstractQuery query; + + /** + * Basic constructor of the {@link QueryBuilder} + * + * @param queryType The type of the query you want to generate + */ + public QueryBuilder(Class queryType) { + try { + query = queryType.newInstance(); + query.defaults(); + } catch (Exception e) { + LOG.error("Could not initialize query: " + e.getMessage()); + } + } + + /** + * Adds a parameter to the building list + * + * @param type The type you want to use + * @param value The value of the type + * @return this class + */ + public QueryBuilder addParameter(QueryParameter type, Object value) { + query.addParameter(type, value); + return this; + } + + /** + * Builds the query + * + * @return the built query + */ + public SQLQuery build() { + return query.build(); + } + + +} diff --git a/src/main/java/de/gnmyt/sqltoolkit/querybuilder/QueryParameter.java b/src/main/java/de/gnmyt/sqltoolkit/querybuilder/QueryParameter.java new file mode 100644 index 0000000..d107e46 --- /dev/null +++ b/src/main/java/de/gnmyt/sqltoolkit/querybuilder/QueryParameter.java @@ -0,0 +1,49 @@ +package de.gnmyt.sqltoolkit.querybuilder; + +/** + * All usable query parameters for the {@link QueryBuilder} + */ +public enum QueryParameter { + + /** + * The name of the table provided as a {@link String} + */ + TABLE_NAME, + + /** + * All 'where'-parameters of the query provided as a {@link java.util.HashMap} + */ + WHERE_LIST, + + /** + * All values of the query provided as a {@link java.util.HashMap} + */ + VALUE_LIST, + + /** + * All 'set'-parameters of the query provided as a {@link java.util.HashMap} + */ + SET_LIST, + + /** + * The selection list of the query provided as a {@link java.util.ArrayList} + */ + SELECT_LIST, + + /** + * The field list of the query provided as a {@link java.util.ArrayList} that contains a {@link de.gnmyt.sqltoolkit.types.TableField} + */ + FIELD_LIST, + + /** + * Tells the {@link de.gnmyt.sqltoolkit.queries.TableCreationQuery} which field is primary + */ + PRIMARY_KEY, + + /** + * The row limit of a query provided as a {@link String} + */ + LIMIT + + +} diff --git a/src/main/java/de/gnmyt/sqltoolkit/querybuilder/SQLQuery.java b/src/main/java/de/gnmyt/sqltoolkit/querybuilder/SQLQuery.java new file mode 100644 index 0000000..f9ebae3 --- /dev/null +++ b/src/main/java/de/gnmyt/sqltoolkit/querybuilder/SQLQuery.java @@ -0,0 +1,73 @@ +package de.gnmyt.sqltoolkit.querybuilder; + +import java.util.Arrays; + +public class SQLQuery { + + private String statement = ""; + private Object[] parameters = new Object[0]; + + /** + * Advanced constructor of the {@link SQLQuery} with prefilled values + * + * @param statement The statement of the query + * @param parameters The query parameters + */ + public SQLQuery(String statement, Object[] parameters) { + this.statement = statement; + this.parameters = parameters; + } + + /** + * Basic constructor of the {@link SQLQuery} + */ + public SQLQuery() { + + } + + /** + * Gets the current statement of the query + * + * @return the current statement + */ + public String getStatement() { + return statement; + } + + /** + * Sets the new statement of the query + * + * @param statement The new query statement + */ + public SQLQuery setStatement(String statement) { + this.statement = statement; + return this; + } + + /** + * Gets the current query parameters + * + * @return the current query parameters + */ + public Object[] getParameters() { + return parameters; + } + + /** + * Sets the new parameters of the query + * + * @param parameters The new query parameters + */ + public SQLQuery setParameters(Object[] parameters) { + this.parameters = parameters; + return this; + } + + @Override + public String toString() { + return "SQLQuery{" + + "statement='" + statement + '\'' + + ", parameters=" + Arrays.toString(parameters) + + '}'; + } +} diff --git a/src/main/java/de/gnmyt/sqltoolkit/querybuilder/StatementBuilder.java b/src/main/java/de/gnmyt/sqltoolkit/querybuilder/StatementBuilder.java new file mode 100644 index 0000000..0af8408 --- /dev/null +++ b/src/main/java/de/gnmyt/sqltoolkit/querybuilder/StatementBuilder.java @@ -0,0 +1,64 @@ +package de.gnmyt.sqltoolkit.querybuilder; + +public class StatementBuilder { + + private final StringBuilder query = new StringBuilder(); + + /** + * Basic constructor of the {@link StatementBuilder} with a prefilled text + * + * @param text The text you want to add + */ + public StatementBuilder(String text) { + append(text); + } + + /** + * Basic constructor of the {@link StatementBuilder} + */ + public StatementBuilder() { + + } + + /** + * Adds a text to the query with spaces + * + * @param text The text you want to add + * @return this class + */ + public StatementBuilder append(String text) { + if (text.isEmpty()) return this; + + if (!query.toString().isEmpty()) query.append(" "); + query.append(text); + return this; + } + + /** + * Adds a text to the query without spaces + * + * @param text The text you want to add + * @return this class + */ + public StatementBuilder appendDefault(String text) { + if (text.isEmpty()) return this; + + query.append(text); + + return this; + } + + /** + * Builds the query string + * + * @return the built string + */ + public String build() { + return query.toString(); + } + + @Override + public String toString() { + return build(); + } +} diff --git a/src/main/java/de/gnmyt/sqltoolkit/storage/SQLStorageMedium.java b/src/main/java/de/gnmyt/sqltoolkit/storage/SQLStorageMedium.java new file mode 100644 index 0000000..e52717e --- /dev/null +++ b/src/main/java/de/gnmyt/sqltoolkit/storage/SQLStorageMedium.java @@ -0,0 +1,98 @@ +package de.gnmyt.sqltoolkit.storage; + +import de.gnmyt.sqltoolkit.drivers.MySQLConnection; + +import java.util.ArrayList; +import java.util.HashMap; + +public abstract class SQLStorageMedium extends SQLTable { + + /** + * The basic constructor of the {@link SQLStorageMedium} + * + * @param connection The mysql connection you want to use + */ + public SQLStorageMedium(MySQLConnection connection) { + super(connection); + } + + @Override + protected void tableFields() { + string("keyName", 255, ""); + string("value", 2000, ""); + } + + /** + * Checks if a key exists in the storage medium + * + * @param key The key you want to check + * @return true if the key exists, otherwise false + */ + public boolean exists(String key) { + return select().where("keyName", key).getResult().exists(); + } + + /** + * Inserts a key into the storage medium + * + * @param key The key you want to insert + * @param value The value you want to insert + */ + public void insert(String key, String value) { + insert().value("keyName", key).value("value", value).execute(); + } + + /** + * Updates a key in the storage medium + * + * @param key The key you want to use + * @param value The value you want to update + */ + public void update(String key, String value) { + update().where("keyName", key).set("value", value).execute(); + } + + /** + * Deletes a key from the storage medium + * + * @param key The key you want to delete + */ + public void delete(String key) { + delete().where("keyName", key).execute(); + } + + /** + * Gets the value of a key + * + * @param key The key of the value you want to get + * @return the value you want to get + */ + public String get(String key) { + return select().where("keyName", key).getResult().getString("value"); + } + + /** + * Gets all entries from the storage medium + * + * @return the entries from the storage medium + */ + public ArrayList> getEntries() { + return select().getResult().getList(); + } + + /** + * Inserts or updates the key of the storage medium. + * If the entry is currently in the storage medium, it updates it. Otherwise, it will insert it + * + * @param key The key you want to insert / update + * @param value The value you want to insert / update + */ + public void insertOrUpdate(String key, String value) { + if (exists(key)) { + update(key, value); + } else { + insert(key, value); + } + } + +} diff --git a/src/main/java/de/gnmyt/sqltoolkit/storage/SQLTable.java b/src/main/java/de/gnmyt/sqltoolkit/storage/SQLTable.java new file mode 100644 index 0000000..a4ea3d0 --- /dev/null +++ b/src/main/java/de/gnmyt/sqltoolkit/storage/SQLTable.java @@ -0,0 +1,188 @@ +package de.gnmyt.sqltoolkit.storage; + +import de.gnmyt.sqltoolkit.drivers.MySQLConnection; +import de.gnmyt.sqltoolkit.manager.*; +import de.gnmyt.sqltoolkit.queries.TableCreationQuery; +import de.gnmyt.sqltoolkit.querybuilder.QueryParameter; +import de.gnmyt.sqltoolkit.querybuilder.SQLQuery; +import de.gnmyt.sqltoolkit.types.SQLType; +import de.gnmyt.sqltoolkit.types.TableField; + +import java.util.ArrayList; + +public abstract class SQLTable { + + private final MySQLConnection connection; + private ArrayList tableFields; + + /** + * The basic constructor of the {@link SQLTable} + * + * @param connection The mysql connection you want to use + */ + public SQLTable(MySQLConnection connection) { + this.connection = connection; + } + + protected abstract String tableName(); + + protected abstract void tableFields(); + + /** + * Adds a string to the table (without allowNull) + * + * @param name The name of the string you want to add + * @param length The length of the string you want to add + * @param defaultValue The default value of the string you want to add (leave empty if you don't want to use one) + * @param extras The extras you want to add to the string + */ + protected void string(String name, int length, String defaultValue, String... extras) { + custom(SQLType.STRING.getValue(), name, length, false, defaultValue, extras); + } + + /** + * Adds a string to the table (with allowNull) + * + * @param name The name of the string you want to add + * @param length The length of the string you want to add + * @param allowNull true if you want to allow a NULL in the field, otherwise false + * @param defaultValue The default value of the string you want to add (leave empty if you don't want to use one) + * @param extras The extras you want to add to the string + */ + protected void string(String name, int length, boolean allowNull, String defaultValue, String... extras) { + custom(SQLType.STRING.getValue(), name, length, allowNull, defaultValue, extras); + } + + /** + * Adds an integer to the table (without allowNull) + * + * @param name The name of the integer you want to add + * @param length The length of the integer you want to add + * @param defaultValue The default value of the integer you want to add (leave empty if you don't want to use one) + * @param extras The extras you want to add to the integer + */ + protected void integer(String name, int length, String defaultValue, String... extras) { + custom(SQLType.INTEGER.getValue(), name, length, false, defaultValue, extras); + } + + /** + * Adds an integer to the table (with allowNull) + * + * @param name The name of the integer you want to add + * @param length The length of the integer you want to add + * @param allowNull true if you want to allow a NULL in the field, otherwise false + * @param defaultValue The default value of the integer you want to add (leave empty if you don't want to use one) + * @param extras The extras you want to add to the integer + */ + protected void integer(String name, int length, boolean allowNull, String defaultValue, String... extras) { + custom(SQLType.INTEGER.getValue(), name, length, allowNull, defaultValue, extras); + } + + /** + * Adds a boolean to the table (without allowNull) + * + * @param name The name of the boolean you want to add + * @param extras The extras you want to add to the boolean + */ + protected void bool(String name, String... extras) { + custom(SQLType.BOOLEAN.getValue(), name, 1, false, "", extras); + } + + /** + * Adds a custom field to the table + * + * @param type The type of the field + * @param name The name of the field + * @param length The length of the field + * @param allowNull true if you want to allow a NULL in the field, otherwise false + * @param defaultValue The default value of the field + * @param extras The extras that you want to add + */ + protected void custom(String type, String name, int length, boolean allowNull, String defaultValue, String... extras) { + custom(new TableField(name, type, length, allowNull, defaultValue).setExtras(extras)); + } + + /** + * Adds a table field to the table + * + * @param tableField The table field you want to add + */ + public void custom(TableField tableField) { + tableFields.add(tableField); + } + + /** + * Adds a custom table field to the table + * + * @param name The name of the column + * @return the manager of the table field + */ + protected CustomTableFieldManager custom(String name) { + return new CustomTableFieldManager(this).name(name); + } + + /** + * Adds a custom table field to the table + * + * @return the manager of the table field + */ + protected CustomTableFieldManager custom() { + return new CustomTableFieldManager(this); + } + + /** + * Gets the database selection from the current the table + * + * @return the database selection + */ + public SelectionManager select() { + return connection.selectFrom(tableName()); + } + + /** + * Gets the update manager of the current table + * + * @return the update manager + */ + public UpdateManager update() { + return connection.updateTo(tableName()); + } + + /** + * Gets the insert manager of the current table + * + * @return the insert manager + */ + public InsertManager insert() { + return connection.insertTo(tableName()); + } + + /** + * Gets the deletion manager of the current table + * + * @return the deletion manager + */ + public DeletionManager delete() { + return connection.deleteFrom(tableName()); + } + + /** + * Creates the table + */ + public void create() { + tableFields = new ArrayList<>(); + + // Add table fields + integer("id", 255, false, "", "AUTO_INCREMENT"); + tableFields(); + + SQLQuery query = connection.createQuery(TableCreationQuery.class) + .addParameter(QueryParameter.TABLE_NAME, tableName()) + .addParameter(QueryParameter.PRIMARY_KEY, "id") + .addParameter(QueryParameter.FIELD_LIST, tableFields) + .build(); + + connection.update(query); + } + +} diff --git a/src/main/java/de/gnmyt/sqltoolkit/types/SQLType.java b/src/main/java/de/gnmyt/sqltoolkit/types/SQLType.java new file mode 100644 index 0000000..4a5d2e9 --- /dev/null +++ b/src/main/java/de/gnmyt/sqltoolkit/types/SQLType.java @@ -0,0 +1,37 @@ +package de.gnmyt.sqltoolkit.types; + +public enum SQLType { + + VARCHAR("VARCHAR"), + STRING("TEXT"), + INTEGER("INT"), + DATE("DATE"), + DATETIME("DATETIME"), + TIMESTAMP("TIMESTAMP"), + TIME("TIME"), + YEAR("YEAR"), + BOOLEAN("TINYINT"), + BIG_INTEGER("BIGINT"), + FLOAT("FLOAT"); + + private final String value; + + /** + * Basic constructor of the {@link SQLType} enum + * + * @param value The value of the type + */ + SQLType(String value) { + this.value = value; + } + + /** + * Get the value of the chosen enum + * + * @return + */ + public String getValue() { + return value; + } + +} diff --git a/src/main/java/de/gnmyt/sqltoolkit/types/TableField.java b/src/main/java/de/gnmyt/sqltoolkit/types/TableField.java new file mode 100644 index 0000000..fab06d8 --- /dev/null +++ b/src/main/java/de/gnmyt/sqltoolkit/types/TableField.java @@ -0,0 +1,217 @@ +package de.gnmyt.sqltoolkit.types; + +import de.gnmyt.sqltoolkit.querybuilder.StatementBuilder; + +public class TableField { + + private String name = "default"; + private String type = SQLType.STRING.getValue(); + private boolean allowNull = false; + private String[] extras = new String[0]; + private int length = 0; + private Object defaultValue; + + /** + * Basic constructor of the {@link TableField} + * + * @param name The name of the field + * @param type The type of the field + * @param length The length of the field + * @param allowNull true if you want to allow a NULL in the field, otherwise false + * @param defaultValue The default value of the field + */ + public TableField(String name, String type, int length, boolean allowNull, Object defaultValue) { + this.name = name; + this.type = type; + this.length = length; + this.allowNull = allowNull; + this.defaultValue = defaultValue; + } + + /** + * Simple constructor of the {@link TableField} + * + * @param name The name of the field + */ + public TableField(String name) { + this.name = name; + } + + /** + * Simple constructor with no prefilled variables + */ + public TableField() { + + } + + /** + * Gets the name of the field + * + * @return the name of the field + */ + public String getName() { + return name; + } + + /** + * Sets the name of the field + * + * @param name The new name of the field + * @return this class + */ + public TableField setName(String name) { + this.name = name; + return this; + } + + /** + * Gets the type of the field + * + * @return the type of the field + */ + public String getType() { + return type; + } + + /** + * Sets the type of the field + * + * @param type The new type of the field + * @return this class + */ + public TableField setType(String type) { + this.type = type; + return this; + } + + /** + * Sets the type of the field (with a sql type) + * + * @param type The new type of the field + * @return this class + */ + public TableField setType(SQLType type) { + this.type = type.getValue(); + return this; + } + + /** + * Gets the length of the field + * + * @return the length of the field + */ + public int getLength() { + return length; + } + + /** + * Sets the length of the field + * + * @param length The new length of the field + * @return this class + */ + public TableField setLength(int length) { + this.length = length; + return this; + } + + /** + * Gets the extra of the field + * + * @return the extra of the field + */ + public String[] getExtras() { + return extras; + } + + + /** + * Sets the extras of the field + * + * @param extras The extras you want to add + * @return this class + */ + public TableField setExtras(String... extras) { + this.extras = extras; + return this; + } + + /** + * Gets the extras of the field as a string + * + * @return the extras of the field as a string + */ + public String getExtraString() { + StatementBuilder extras = new StatementBuilder(); + for (int i = 0; i < getExtras().length; i++) + extras.append(getExtras()[i]); + return extras.build(); + } + + /** + * Gets the allowNull variable as sql string + * + * @return the allowNull variable as sql string + */ + public String getNullAsSQL() { + return !isAllowNull() ? "NOT NULL" : ""; + } + + /** + * Gets the default value of the field + * + * @return the default value of the field + */ + public String getDefaultValue() { + if (defaultValue == null) return ""; + if (defaultValue instanceof String && (((String) defaultValue).isEmpty())) return ""; + + return "DEFAULT " + (defaultValue instanceof String ? "'" + defaultValue + "'" : defaultValue); + } + + /** + * Sets the default value of the field + * + * @param defaultValue The new default value of the field + * @return this class + */ + public TableField setDefaultValue(Object defaultValue) { + this.defaultValue = defaultValue; + return this; + } + + /** + * Checks if the field is allowed to have a NULL + * + * @return true if the field is NULL, otherwise false + */ + public boolean isAllowNull() { + return allowNull; + } + + /** + * Sets the allowNull variable of the field + * + * @param allowNull true if you want to allow a NULL in the field, otherwise false + * @return this class + */ + public TableField setAllowNull(boolean allowNull) { + this.allowNull = allowNull; + return this; + } + + /** + * Gets the generated sql row + * + * @return the generated sql row + */ + public String generateSQLRow() { + return String.format("`%s` %s%s%s%s%s", getName(), getType(), + getLength() == 0 ? "" : "(" + getLength() + ")", + getNullAsSQL().isEmpty() ? "" : " " + getNullAsSQL(), + getDefaultValue().isEmpty() ? "" : " " + getDefaultValue(), + getExtraString().isEmpty() ? "" : " " + getExtraString()); + } + + +}