7 Commits

Author SHA1 Message Date
Bryan Terce
1e95b818eb 0.2.0 Update 2019-06-22 12:12:27 -07:00
Bryan Terce
688ea9d46b Manually fix README 2019-06-22 12:11:29 -07:00
Bryan Terce
dd6d574479 Update README 2019-06-22 12:09:59 -07:00
Bryan Terce
1f6091eb95 Add synchronous execution flag 2019-06-22 12:09:17 -07:00
Bryan Terce
74d4918f44 Fix lifespan syntax 2019-06-22 12:05:22 -07:00
Bryan Terce
39bb3b0b72 Add some warnings for misusing SQL injection protection (#4) 2018-05-09 15:35:47 -07:00
Bryan Terce
cef0c4c816 Add connection lifespan option 2018-02-19 13:24:34 -08:00
6 changed files with 129 additions and 47 deletions

View File

@@ -3,35 +3,21 @@
> Sensible SQL support for Skript.
---
### Expression `Data Source` => `datasource`
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 provided uses a MySQL database.
#### Syntax
```
[the] data(base|[ ]source) [(of|at)] %string%
```
#### Examples
```
set {sql} to the database "mysql://localhost:3306/mydatabase?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.
<p>
If a single variable, such as `{test}`, is passed, the variable will be set to the number of
affected rows.
<p>
If a list variable, such as `{test::*}`, is passed, the query result will be mapped to the list
variable in the form `{test::<column name>::<row number>}`
Specifying `synchronously` will make skript-db execute the query on the event thread, which is useful for async
events. Note that skript-db will ignore this flag if you attempt to run this on the main thread.
#### Syntax
```
execute %string% (in|on) %datasource% [and store [[the] (output|result)[s]] (to|in) [the] [var[iable]] %-objects%]
[synchronously] execute %string% (in|on) %datasource% [and store [[the] (output|result)[s]] (to|in) [the] [var[iable]] %-objects%]
```
#### Examples
@@ -39,7 +25,7 @@ execute %string% (in|on) %datasource% [and store [[the] (output|result)[s]] (to|
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::*}
execute "select * where player=%{player}%" in {sql} and store the result in {output::*}
```
---
@@ -70,3 +56,20 @@ execute unsafe {fully dynamic query} in {sql}
---
### Expression `Data Source` => `datasource`
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 provided uses a MySQL database.
#### Syntax
```
[the] data(base|[ ]source) [(of|at)] %string% [with [a] [max[imum]] [connection] life[ ]time of %timespan%]"
```
#### Examples
```
set {sql} to the database "mysql://localhost:3306/mydatabase?user=admin&password=12345&useSSL=false"
```
---

View File

@@ -1,5 +1,5 @@
group 'com.btk5h.skript-db'
version '0.1.1'
version '0.2.0'
buildscript {
repositories {

View File

@@ -34,24 +34,27 @@ import ch.njol.util.Kleenean;
/**
* 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.
*
* <p>
* If a single variable, such as `{test}`, is passed, the variable will be set to the number of
* affected rows.
*
* <p>
* If a list variable, such as `{test::*}`, is passed, the query result will be mapped to the list
* variable in the form `{test::<column name>::<row number>}`
*
* Specifying `synchronously` will make skript-db execute the query on the event thread, which is useful for async
* events. Note that skript-db will ignore this flag if you attempt to run this on the main thread.
*
* @name Execute Statement
* @pattern execute %string% (in|on) %datasource% [and store [[the] (output|result)[s]] (to|in)
* @pattern [synchronously] execute %string% (in|on) %datasource% [and store [[the] (output|result)[s]] (to|in)
* [the] [var[iable]] %-objects%]
* @example execute "select * from table" in {sql} and store the result in {output::*}
* @example execute "select * from %{table variable}%" in {sql} and store the result in {output::*}
* @example execute "select * where player=%{player}%" in {sql} and store the result in {output::*}
* @since 0.1.0
*/
public class EffExecuteStatement extends Delay {
static {
Skript.registerEffect(EffExecuteStatement.class,
"execute %string% (in|on) %datasource% " +
"[(1¦synchronously)] execute %string% (in|on) %datasource% " +
"[and store [[the] (output|result)[s]] (to|in) [the] [var[iable]] %-objects%]");
}
@@ -65,25 +68,43 @@ public class EffExecuteStatement extends Delay {
private VariableString var;
private boolean isLocal;
private boolean isList;
private boolean isSync;
private void continueScriptExecution(Event e, String res) {
lastError = res;
if (getNext() != null) {
TriggerItem.walk(getNext(), e);
}
}
@Override
protected void execute(Event e) {
CompletableFuture<String> sql =
CompletableFuture.supplyAsync(() -> executeStatement(e), threadPool);
boolean isMainThread = Bukkit.isPrimaryThread();
sql.whenComplete((res, err) -> {
if (err != null) {
err.printStackTrace();
if (isSync && !isMainThread) {
String result = executeStatement(e);
continueScriptExecution(e, result);
} else {
if (isMainThread) {
Skript.warning("A SQL query was attempted on the main thread!");
}
Bukkit.getScheduler().runTask(SkriptDB.getInstance(), () -> {
lastError = res;
CompletableFuture<String> sql =
CompletableFuture.supplyAsync(() -> executeStatement(e), threadPool);
if (getNext() != null) {
TriggerItem.walk(getNext(), e);
sql.whenComplete((res, err) -> {
if (err != null) {
err.printStackTrace();
}
if (isSync) {
continueScriptExecution(e, res);
} else {
Bukkit.getScheduler().runTask(SkriptDB.getInstance(), () -> continueScriptExecution(e, res));
}
});
});
}
}
@Override
@@ -145,16 +166,41 @@ public class EffExecuteStatement extends Delay {
StringBuilder sb = new StringBuilder();
List<Object> parameters = new ArrayList<>();
Object[] objects = SkriptUtil.getTemplateString(((VariableString) query));
for (Object o : objects) {
for (int i = 0; i < objects.length; i++) {
Object o = objects[i];
if (o instanceof String) {
sb.append(o);
} else {
Expression<?> expr = SkriptUtil.getExpressionFromInfo(o);
String before = getString(objects, i - 1);
String after = getString(objects, i + 1);
boolean standaloneString = false;
if (before != null && after != null) {
if (before.endsWith("'") && after.endsWith("'")) {
standaloneString = true;
}
}
Object expressionValue = expr.getSingle(e);
if (expr instanceof ExprUnsafe) {
sb.append(expr.getSingle(e));
sb.append(expressionValue);
if (standaloneString && expressionValue instanceof String) {
String rawExpression = ((ExprUnsafe) expr).getRawExpression();
Skript.warning(
String.format("Unsafe may have been used unnecessarily. Try replacing 'unsafe %1$s' with %1$s",
rawExpression));
}
} else {
parameters.add(expr.getSingle(e));
parameters.add(expressionValue);
sb.append('?');
if (standaloneString) {
Skript.warning("Do not surround expressions with quotes!");
}
}
}
}
@@ -168,6 +214,20 @@ public class EffExecuteStatement extends Delay {
return stmt;
}
private String getString(Object[] objects, int index) {
if (index < 0 || index >= objects.length) {
return null;
}
Object object = objects[index];
if (object instanceof String) {
return (String) object;
}
return null;
}
private void setVariable(Event e, String name, Object obj) {
Variables.setVariable(name.toLowerCase(Locale.ENGLISH), obj, e, isLocal);
}
@@ -212,6 +272,7 @@ public class EffExecuteStatement extends Delay {
}
dataSource = (Expression<HikariDataSource>) exprs[1];
Expression<?> expr = exprs[2];
isSync = parseResult.mark == 1;
if (expr instanceof Variable) {
Variable<?> varExpr = (Variable<?>) expr;
var = SkriptUtil.getVariableName(varExpr);

View File

@@ -12,6 +12,7 @@ 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.skript.util.Timespan;
import ch.njol.util.Kleenean;
/**
@@ -22,7 +23,7 @@ import ch.njol.util.Kleenean;
*
* @name Data Source
* @index -1
* @pattern [the] data(base|[ ]source) [(of|at)] %string%
* @pattern [the] data(base|[ ]source) [(of|at)] %string% [with [a] [max[imum]] [connection] life[ ]time of %timespan%]"
* @return datasource
* @example set {sql} to the database "mysql://localhost:3306/mydatabase?user=admin&password=12345&useSSL=false"
* @since 0.1.0
@@ -30,12 +31,14 @@ import ch.njol.util.Kleenean;
public class ExprDataSource extends SimpleExpression<HikariDataSource> {
static {
Skript.registerExpression(ExprDataSource.class, HikariDataSource.class,
ExpressionType.COMBINED, "[the] data(base|[ ]source) [(of|at)] %string%");
ExpressionType.COMBINED, "[the] data(base|[ ]source) [(of|at)] %string% " +
"[with [a] [max[imum]] [connection] life[ ]time of %-timespan%]");
}
private static Map<String, HikariDataSource> connectionCache = new HashMap<>();
private Expression<String> url;
private Expression<Timespan> maxLifetime;
@Override
protected HikariDataSource[] get(Event e) {
@@ -55,6 +58,14 @@ public class ExprDataSource extends SimpleExpression<HikariDataSource> {
HikariDataSource ds = new HikariDataSource();
ds.setJdbcUrl(jdbcUrl);
if (maxLifetime != null) {
Timespan l = maxLifetime.getSingle(e);
if (l != null) {
ds.setMaxLifetime(l.getMilliSeconds());
}
}
connectionCache.put(jdbcUrl, ds);
return new HikariDataSource[]{ds};
@@ -80,6 +91,7 @@ public class ExprDataSource extends SimpleExpression<HikariDataSource> {
public boolean init(Expression<?>[] exprs, int matchedPattern, Kleenean isDelayed,
SkriptParser.ParseResult parseResult) {
url = (Expression<String>) exprs[0];
maxLifetime = (Expression<Timespan>) exprs[1];
return true;
}
}

View File

@@ -25,11 +25,16 @@ public class ExprUnsafe extends SimpleExpression<String> {
"unsafe %string%");
}
private Expression<String> str;
private Expression<String> stringExpression;
private String rawExpression;
public String getRawExpression() {
return rawExpression;
}
@Override
protected String[] get(Event e) {
return str.getArray(e);
return stringExpression.getArray(e);
}
@Override
@@ -44,14 +49,15 @@ public class ExprUnsafe extends SimpleExpression<String> {
@Override
public String toString(Event e, boolean debug) {
return "unsafe " + str.toString(e, debug);
return "unsafe " + stringExpression.toString(e, debug);
}
@SuppressWarnings("unchecked")
@Override
public boolean init(Expression<?>[] exprs, int matchedPattern, Kleenean isDelayed,
SkriptParser.ParseResult parseResult) {
str = (Expression<String>) exprs[0];
stringExpression = (Expression<String>) exprs[0];
rawExpression = parseResult.expr.substring("unsafe".length()).trim();
return true;
}
}

View File

@@ -1,4 +1,4 @@
name: skript-db
version: 0.1.1
version: 0.2.0
main: com.btk5h.skriptdb.SkriptDB
depend: [Skript]