commit 9f414387b6afe15f851657f174f51ddedb3e769d Author: Bryan Terce Date: Sat Nov 18 19:49:49 2017 -0800 Initial commit diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..06eee9e --- /dev/null +++ b/.editorconfig @@ -0,0 +1,13 @@ +# editorconfig.org +root = true + +[*] +indent_style = space +indent_size = 2 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true + +[*.java] +continuation_indent_size = 4 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..54a42c3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,10 @@ +## OSX +*.DS_Store + +## Gradle +.gradle +build/ + +## IntelliJ +.idea/ +*.iml diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..60ea6f7 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Bryan Terce + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..12c369d --- /dev/null +++ b/README.md @@ -0,0 +1,64 @@ +# skript-db + +> Awesome direct database access for Skript + +## Syntax + +### Expression `Data Source` => `datasource` + +This stores the connection information for a data source. This should be saved to a variable in a `script load` event or manually through an effect command. + +The url format for your database may vary! The example below uses a MySQL database. + +#### Syntax + +`[the] data(base|[ ]source) [(of|at)] %string%` + +#### Example + +``` +set {sql} to the database "mysql://localhost:3306/sys?user=admin&password=12345&useSSL=false" +``` + +### Effect `Execute Statement` + +Executes a statement on a database and optionally stores the result in a variable. Expressions embedded in the query will be escaped to avoid SQL injection. + +If a single variable, such as `{test}`, is passed, the variable will be set to the number of affected rows. + +If a list variable, such as `{test::*}`, is passed, the query result will be mapped to the list variable in the form `{test::::}` + +#### Syntax + +`execute %text% (in|on) %datasource% + [and store [[the] (output|result)[s]] (to|in) [the] [var[iable]] %variable%]` + +#### Example + +``` +execute "select * from table" in {sql} and store the result in {output::*} +execute "select * from %{table variable}%" in {sql} and store the result in {output::*} +``` + +### Expression `Unsafe Expression` => `text` + +Opts out of automatic SQL injection protection for a specific expression in a statement. + +#### Syntax + +`unsafe %text%` + +#### Example + +``` +execute "select %unsafe {columns variable}% from %{table variable}%" in {sql} and store the result in {output::*} +execute unsafe {fully dynamic query} in {sql} +``` + +### Expression `Last Data Source Error` => `text` + +Stores the error from the last executed statement, if there was one. + +#### Syntax + +`[the] [last] (sql|db|data(base|[ ]source)) error` diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..c392572 --- /dev/null +++ b/build.gradle @@ -0,0 +1,35 @@ +group 'com.btk5h.skript-db' +version '0.1.0' + +buildscript { + repositories { + jcenter() + } + dependencies { + classpath 'com.github.jengelman.gradle.plugins:shadow:2.0.1' + } +} + +apply plugin: 'com.github.johnrengelman.shadow' +apply plugin: 'java' + +sourceCompatibility = 1.8 + +repositories { + mavenCentral() + maven { + url 'https://hub.spigotmc.org/nexus/content/repositories/snapshots/' + } + maven { + url 'https://oss.sonatype.org/content/groups/public/' + } + maven { + url 'http://maven.njol.ch/repo/' + } +} + +dependencies { + shadow 'org.spigotmc:spigot-api:1.11-R0.1-SNAPSHOT' + shadow 'ch.njol:skript:2.2-SNAPSHOT' + compile 'com.zaxxer:HikariCP:2.6.2' +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..807526f Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..3f744f9 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Thu Aug 24 18:49:02 PDT 2017 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..4453cce --- /dev/null +++ b/gradlew @@ -0,0 +1,172 @@ +#!/usr/bin/env sh + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save ( ) { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..f955316 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,84 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..3611235 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,2 @@ +rootProject.name = 'skript-db' + diff --git a/src/main/java/com/btk5h/skriptdb/SkriptDB.java b/src/main/java/com/btk5h/skriptdb/SkriptDB.java new file mode 100644 index 0000000..ab026b7 --- /dev/null +++ b/src/main/java/com/btk5h/skriptdb/SkriptDB.java @@ -0,0 +1,84 @@ +/* + * MIT License + * + * Copyright (c) 2016 Bryan Terce + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +package com.btk5h.skriptdb; + +import org.bukkit.plugin.java.JavaPlugin; + +import java.io.IOException; +import java.sql.SQLException; + +import javax.sql.rowset.RowSetFactory; +import javax.sql.rowset.RowSetProvider; + +import ch.njol.skript.Skript; +import ch.njol.skript.SkriptAddon; + +public final class SkriptDB extends JavaPlugin { + + private static SkriptDB instance; + private static SkriptAddon addonInstance; + + private static RowSetFactory rowSetFactory; + + public SkriptDB() { + if (instance == null) { + instance = this; + } else { + throw new IllegalStateException(); + } + } + + @Override + public void onEnable() { + try { + rowSetFactory = RowSetProvider.newFactory(); + + getAddonInstance().loadClasses("com.btk5h.skriptdb.skript"); + } catch (SQLException e) { + throw new RuntimeException(e); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public static SkriptAddon getAddonInstance() { + if (addonInstance == null) { + addonInstance = Skript.registerAddon(getInstance()); + } + return addonInstance; + } + + public static SkriptDB getInstance() { + if (instance == null) { + throw new IllegalStateException(); + } + return instance; + } + + public static RowSetFactory getRowSetFactory() { + return rowSetFactory; + } +} diff --git a/src/main/java/com/btk5h/skriptdb/SkriptUtil.java b/src/main/java/com/btk5h/skriptdb/SkriptUtil.java new file mode 100644 index 0000000..290094b --- /dev/null +++ b/src/main/java/com/btk5h/skriptdb/SkriptUtil.java @@ -0,0 +1,123 @@ +package com.btk5h.skriptdb; + +import org.bukkit.event.Event; + +import java.lang.reflect.Field; +import java.util.Arrays; +import java.util.Optional; +import java.util.Set; + +import ch.njol.skript.Skript; +import ch.njol.skript.effects.Delay; +import ch.njol.skript.lang.Expression; +import ch.njol.skript.lang.Variable; +import ch.njol.skript.lang.VariableString; + +public class SkriptUtil { + + private static final Field STRING; + private static final Field SIMPLE; + private static final Field DELAYED; + private static final Field EXPR; + private static final Field VARIABLE_NAME; + + static { + Field _FIELD = null; + try { + _FIELD = VariableString.class.getDeclaredField("string"); + _FIELD.setAccessible(true); + } catch (NoSuchFieldException e) { + Skript.error("Skript's 'string' field could not be resolved."); + e.printStackTrace(); + } + STRING = _FIELD; + + try { + _FIELD = VariableString.class.getDeclaredField("simple"); + _FIELD.setAccessible(true); + } catch (NoSuchFieldException e) { + Skript.error("Skript's 'simple' field could not be resolved."); + e.printStackTrace(); + } + SIMPLE = _FIELD; + + try { + _FIELD = Delay.class.getDeclaredField("delayed"); + _FIELD.setAccessible(true); + } catch (NoSuchFieldException e) { + e.printStackTrace(); + Skript.warning("Skript's 'delayed' method could not be resolved. Some Skript warnings may " + + "not be available."); + } + DELAYED = _FIELD; + + try { + Optional> expressionInfo = Arrays.stream(VariableString.class.getDeclaredClasses()) + .filter(cls -> cls.getSimpleName().equals("ExpressionInfo")) + .findFirst(); + if (expressionInfo.isPresent()) { + Class expressionInfoClass = expressionInfo.get(); + _FIELD = expressionInfoClass.getDeclaredField("expr"); + _FIELD.setAccessible(true); + } else { + Skript.error("Skript's 'ExpressionInfo' class could not be resolved."); + } + } catch (NoSuchFieldException e) { + e.printStackTrace(); + Skript.error("Skript's 'expr' field could not be resolved."); + } + EXPR = _FIELD; + + try { + _FIELD = Variable.class.getDeclaredField("name"); + _FIELD.setAccessible(true); + } catch (NoSuchFieldException e) { + e.printStackTrace(); + Skript.error("Skript's 'variable name' method could not be resolved."); + } + VARIABLE_NAME = _FIELD; + } + + @SuppressWarnings("unchecked") + public static void delay(Event e) { + if (DELAYED != null) { + try { + ((Set) DELAYED.get(null)).add(e); + } catch (IllegalAccessException ignored) { + } + } + } + + public static String getSimpleString(VariableString vs) { + try { + return (String) SIMPLE.get(vs); + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + } + + public static Object[] getTemplateString(VariableString vs) { + try { + return (Object[]) STRING.get(vs); + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + } + + public static Expression getExpressionFromInfo(Object o) { + try { + return (Expression) EXPR.get(o); + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + } + + public static VariableString getVariableName(Variable var) { + try { + return (VariableString) VARIABLE_NAME.get(var); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + return null; + } +} diff --git a/src/main/java/com/btk5h/skriptdb/skript/EffExecuteStatement.java b/src/main/java/com/btk5h/skriptdb/skript/EffExecuteStatement.java new file mode 100644 index 0000000..92a984b --- /dev/null +++ b/src/main/java/com/btk5h/skriptdb/skript/EffExecuteStatement.java @@ -0,0 +1,209 @@ +package com.btk5h.skriptdb.skript; + +import com.btk5h.skriptdb.SkriptDB; +import com.btk5h.skriptdb.SkriptUtil; +import com.zaxxer.hikari.HikariDataSource; + +import org.bukkit.Bukkit; +import org.bukkit.event.Event; +import org.eclipse.jdt.annotation.Nullable; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import javax.sql.rowset.CachedRowSet; + +import ch.njol.skript.Skript; +import ch.njol.skript.effects.Delay; +import ch.njol.skript.lang.Expression; +import ch.njol.skript.lang.SkriptParser; +import ch.njol.skript.lang.TriggerItem; +import ch.njol.skript.lang.Variable; +import ch.njol.skript.lang.VariableString; +import ch.njol.skript.variables.Variables; +import ch.njol.util.Kleenean; + +public class EffExecuteStatement extends Delay { + static { + Skript.registerEffect(EffExecuteStatement.class, + "execute %string% (in|on) %datasource% " + + "[and store [[the] (output|result)[s]] (to|in) [the] [var[iable]] %-objects%]"); + } + + static String lastError; + + private static final ExecutorService threadPool = + Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); + + private Expression query; + private Expression dataSource; + private VariableString var; + private boolean isLocal; + private boolean isList; + + @Override + protected void execute(Event e) { + CompletableFuture sql = + CompletableFuture.supplyAsync(() -> executeStatement(e), threadPool); + + sql.whenComplete((res, err) -> { + if (err != null) { + err.printStackTrace(); + } + + Bukkit.getScheduler().runTask(SkriptDB.getInstance(), () -> { + lastError = res; + + if (getNext() != null) { + TriggerItem.walk(getNext(), e); + } + }); + }); + } + + @Override + protected TriggerItem walk(Event e) { + debug(e, true); + SkriptUtil.delay(e); + execute(e); + return null; + } + + private String executeStatement(Event e) { + HikariDataSource ds = dataSource.getSingle(e); + + if (ds == null) { + return "Data source is not set"; + } + + try (Connection conn = ds.getConnection(); + PreparedStatement stmt = createStatement(e, conn)) { + + boolean hasResultSet = stmt.execute(); + + if (var != null) { + String baseVariable = var.toString(e) + .toLowerCase(Locale.ENGLISH); + if (isList) { + baseVariable = baseVariable.substring(0, baseVariable.length() - 1); + } + + if (hasResultSet) { + CachedRowSet crs = SkriptDB.getRowSetFactory().createCachedRowSet(); + crs.populate(stmt.getResultSet()); + + if (isList) { + populateVariable(e, crs, baseVariable); + } else { + crs.last(); + setVariable(e, baseVariable, crs.getRow()); + } + } else if (!isList) { + setVariable(e, baseVariable, stmt.getUpdateCount()); + } + } + } catch (SQLException ex) { + return ex.getMessage(); + } + return null; + } + + private PreparedStatement createStatement(Event e, Connection conn) throws SQLException { + if (!(query instanceof VariableString)) { + return conn.prepareStatement(query.getSingle(e)); + } + + if (((VariableString) query).isSimple()) { + return conn.prepareStatement(SkriptUtil.getSimpleString(((VariableString) query))); + } + + StringBuilder sb = new StringBuilder(); + List parameters = new ArrayList<>(); + Object[] objects = SkriptUtil.getTemplateString(((VariableString) query)); + for (Object o : objects) { + if (o instanceof String) { + sb.append(o); + } else { + Expression expr = SkriptUtil.getExpressionFromInfo(o); + if (expr instanceof ExprUnsafe) { + sb.append(expr.getSingle(e)); + } else { + parameters.add(expr.getSingle(e)); + sb.append('?'); + } + } + } + + PreparedStatement stmt = conn.prepareStatement(sb.toString()); + + for (int i = 0; i < parameters.size(); i++) { + stmt.setObject(i + 1, parameters.get(i)); + } + + return stmt; + } + + private void setVariable(Event e, String name, Object obj) { + Variables.setVariable(name.toLowerCase(Locale.ENGLISH), obj, e, isLocal); + } + + private void populateVariable(Event e, CachedRowSet crs, String baseVariable) + throws SQLException { + ResultSetMetaData meta = crs.getMetaData(); + int columnCount = meta.getColumnCount(); + + for (int i = 1; i <= columnCount; i++) { + String label = meta.getColumnLabel(i); + setVariable(e, baseVariable + label, label); + } + + int rowNumber = 1; + while (crs.next()) { + for (int i = 1; i <= columnCount; i++) { + setVariable(e, baseVariable + meta.getColumnLabel(i).toLowerCase(Locale.ENGLISH) + + Variable.SEPARATOR + rowNumber, crs.getObject(i)); + } + rowNumber++; + } + } + + @Override + public String toString(@Nullable Event e, boolean debug) { + return "execute " + query.toString(e, debug) + " in " + dataSource.toString(e, debug); + } + + @SuppressWarnings("unchecked") + @Override + public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelayed, + SkriptParser.ParseResult parseResult) { + Expression statementExpr = (Expression) exprs[0]; + if (statementExpr instanceof VariableString || statementExpr instanceof ExprUnsafe) { + query = statementExpr; + } else { + Skript.error("Database statements must be string literals. If you must use an expression, " + + "you may use \"%unsafe (your expression)%\", but keep in mind, you may be vulnerable " + + "to SQL injection attacks!"); + return false; + } + dataSource = (Expression) exprs[1]; + Expression expr = exprs[2]; + if (expr instanceof Variable) { + Variable varExpr = (Variable) expr; + var = SkriptUtil.getVariableName(varExpr); + isLocal = varExpr.isLocal(); + isList = varExpr.isList(); + } else if (expr != null) { + Skript.error(expr + " is not a variable"); + return false; + } + return true; + } +} diff --git a/src/main/java/com/btk5h/skriptdb/skript/ExprDBError.java b/src/main/java/com/btk5h/skriptdb/skript/ExprDBError.java new file mode 100644 index 0000000..0f9d900 --- /dev/null +++ b/src/main/java/com/btk5h/skriptdb/skript/ExprDBError.java @@ -0,0 +1,42 @@ +package com.btk5h.skriptdb.skript; + +import org.bukkit.event.Event; + +import ch.njol.skript.Skript; +import ch.njol.skript.lang.Expression; +import ch.njol.skript.lang.ExpressionType; +import ch.njol.skript.lang.SkriptParser; +import ch.njol.skript.lang.util.SimpleExpression; +import ch.njol.util.Kleenean; + +public class ExprDBError extends SimpleExpression { + static { + Skript.registerExpression(ExprDBError.class, String.class, + ExpressionType.SIMPLE, "[the] [last] (sql|db|data(base|[ ]source)) error"); + } + + @Override + protected String[] get(Event e) { + return new String[]{EffExecuteStatement.lastError}; + } + + @Override + public boolean isSingle() { + return true; + } + + @Override + public Class getReturnType() { + return String.class; + } + + @Override + public String toString(Event e, boolean debug) { + return "last database error"; + } + + @Override + public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelayed, SkriptParser.ParseResult parseResult) { + return true; + } +} diff --git a/src/main/java/com/btk5h/skriptdb/skript/ExprDataSource.java b/src/main/java/com/btk5h/skriptdb/skript/ExprDataSource.java new file mode 100644 index 0000000..f565447 --- /dev/null +++ b/src/main/java/com/btk5h/skriptdb/skript/ExprDataSource.java @@ -0,0 +1,61 @@ +package com.btk5h.skriptdb.skript; + +import com.zaxxer.hikari.HikariDataSource; + +import org.bukkit.event.Event; + +import ch.njol.skript.Skript; +import ch.njol.skript.lang.Expression; +import ch.njol.skript.lang.ExpressionType; +import ch.njol.skript.lang.SkriptParser; +import ch.njol.skript.lang.util.SimpleExpression; +import ch.njol.util.Kleenean; + +public class ExprDataSource extends SimpleExpression { + static { + Skript.registerExpression(ExprDataSource.class, HikariDataSource.class, + ExpressionType.COMBINED, "[the] data(base|[ ]source) [(of|at)] %string%"); + } + + private Expression url; + + @Override + protected HikariDataSource[] get(Event e) { + String jdbcUrl = url.getSingle(e); + if (jdbcUrl == null) { + return null; + } + + if (!jdbcUrl.startsWith("jdbc:")) { + jdbcUrl = "jdbc:" + jdbcUrl; + } + + HikariDataSource ds = new HikariDataSource(); + ds.setJdbcUrl(jdbcUrl); + + return new HikariDataSource[] {ds}; + } + + @Override + public boolean isSingle() { + return true; + } + + @Override + public Class getReturnType() { + return HikariDataSource.class; + } + + @Override + public String toString(Event e, boolean debug) { + return "datasource " + url.toString(e, debug); + } + + @SuppressWarnings("unchecked") + @Override + public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelayed, + SkriptParser.ParseResult parseResult) { + url = (Expression) exprs[0]; + return true; + } +} diff --git a/src/main/java/com/btk5h/skriptdb/skript/ExprUnsafe.java b/src/main/java/com/btk5h/skriptdb/skript/ExprUnsafe.java new file mode 100644 index 0000000..c8acd73 --- /dev/null +++ b/src/main/java/com/btk5h/skriptdb/skript/ExprUnsafe.java @@ -0,0 +1,47 @@ +package com.btk5h.skriptdb.skript; + +import org.bukkit.event.Event; + +import ch.njol.skript.Skript; +import ch.njol.skript.lang.Expression; +import ch.njol.skript.lang.ExpressionType; +import ch.njol.skript.lang.SkriptParser; +import ch.njol.skript.lang.util.SimpleExpression; +import ch.njol.util.Kleenean; + +public class ExprUnsafe extends SimpleExpression { + static { + Skript.registerExpression(ExprUnsafe.class, String.class, ExpressionType.COMBINED, + "unsafe %string%"); + } + + private Expression str; + + @Override + protected String[] get(Event e) { + return str.getArray(e); + } + + @Override + public boolean isSingle() { + return true; + } + + @Override + public Class getReturnType() { + return String.class; + } + + @Override + public String toString(Event e, boolean debug) { + return "unsafe " + str.toString(e, debug); + } + + @SuppressWarnings("unchecked") + @Override + public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelayed, + SkriptParser.ParseResult parseResult) { + str = (Expression) exprs[0]; + return true; + } +} diff --git a/src/main/java/com/btk5h/skriptdb/skript/Types.java b/src/main/java/com/btk5h/skriptdb/skript/Types.java new file mode 100644 index 0000000..d26610c --- /dev/null +++ b/src/main/java/com/btk5h/skriptdb/skript/Types.java @@ -0,0 +1,72 @@ +package com.btk5h.skriptdb.skript; + +import com.zaxxer.hikari.HikariDataSource; + +import java.io.NotSerializableException; +import java.io.StreamCorruptedException; + +import ch.njol.skript.classes.ClassInfo; +import ch.njol.skript.classes.Parser; +import ch.njol.skript.classes.Serializer; +import ch.njol.skript.lang.ParseContext; +import ch.njol.skript.registrations.Classes; +import ch.njol.yggdrasil.Fields; + +public class Types { + static { + Classes.registerClass(new ClassInfo<>(HikariDataSource.class, "datasource") + .user("datasources?") + .parser(new Parser() { + @Override + public HikariDataSource parse(String s, ParseContext context) { + return null; + } + + @Override + public String toString(HikariDataSource o, int flags) { + return o.getJdbcUrl(); + } + + @Override + public String toVariableNameString(HikariDataSource o) { + return o.getJdbcUrl(); + } + + @Override + public String getVariableNamePattern() { + return "jdbc:.+"; + } + }) + .serializer(new Serializer() { + @Override + public Fields serialize(HikariDataSource o) throws NotSerializableException { + Fields fields = new Fields(); + fields.putObject("jdbcurl", o.getJdbcUrl()); + return fields; + } + + @Override + public void deserialize(HikariDataSource o, Fields f) throws StreamCorruptedException, + NotSerializableException { + } + + @Override + protected HikariDataSource deserialize(Fields fields) throws StreamCorruptedException, + NotSerializableException { + HikariDataSource ds = new HikariDataSource(); + ds.setJdbcUrl((String) fields.getObject("jdbcurl")); + return ds; + } + + @Override + public boolean mustSyncDeserialization() { + return false; + } + + @Override + public boolean canBeInstantiated(Class c) { + return false; + } + })); + } +} diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml new file mode 100644 index 0000000..aa74f74 --- /dev/null +++ b/src/main/resources/plugin.yml @@ -0,0 +1,4 @@ +name: skript-db +version: 0.1.0 +main: com.btk5h.skriptdb.SkriptDB +depend: [Skript]