Skip to content

Commit

Permalink
Add connection lifespan option
Browse files Browse the repository at this point in the history
  • Loading branch information
btk5h committed Feb 19, 2018
1 parent 3016a3c commit cef0c4c
Showing 1 changed file with 14 additions and 2 deletions.
16 changes: 14 additions & 2 deletions src/main/java/com/btk5h/skriptdb/skript/ExprDataSource.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
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;

/**
Expand All @@ -22,20 +23,22 @@
*
* @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
*/
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) {
Expand All @@ -55,6 +58,14 @@ protected HikariDataSource[] get(Event e) {
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};
Expand All @@ -80,6 +91,7 @@ public String toString(Event e, boolean debug) {
public boolean init(Expression<?>[] exprs, int matchedPattern, Kleenean isDelayed,
SkriptParser.ParseResult parseResult) {
url = (Expression<String>) exprs[0];
maxLifetime = (Expression<Timespan>) exprs[1];
return true;
}
}

0 comments on commit cef0c4c

Please sign in to comment.