Database and queries
com.db.DatabaseManager, com.db.ServerQuery
A dataserver block gives the application one connection to MySQL or MariaDB and one thread that owns it.
Every query goes into that thread's queue and runs in order. Nothing else ever waits on the database: you describe what
should happen when the result arrives, and carry on.
Connecting
dataserver: source env:DB_DSN
export DB_DSN='shop_user:s3cret@tcp(localhost:3306)/shop' # or mysql://shop_user:s3cret@localhost:3306/shop
or, with the password in the file:
dataserver: source localhost shop credentials shop_user s3cret
If the database cannot be reached at startup JBend says so and starts anyway; queries fail until it is back, and the connection is retried as queries arrive. A connection that has gone stale (a MySQL restart, an idle timeout) is noticed and reopened without restarting JBend.
ServerQuery
A query is an object. Creating it queues the SQL; when it has run, its done() method is called with the result.
new ServerQuery(c, "SELECT x, y FROM players WHERE username = ?", name) {
public void done() {
if (failed()) { c.sendMessage("error"); return; }
if (responseSize() == 0) { c.sendMessage("no such player"); return; }
c.sendMessage("pos:" + value("x") + "," + value("y"));
}
};
Queries started inside done() run after it, so a sequence reads top to bottom:
new ServerQuery("SELECT COUNT(*) FROM players WHERE username = ?", name) {
public void done() {
if (count() > 0) { c.sendMessage("taken"); return; }
new ServerQuery("INSERT INTO players (username, x, y) VALUES (?, ?, ?)", name, 110, 815) {
public void done() {
c.sendMessage(failed() ? "error" : "created");
}
};
}
};
A query whose result you do not need is one line:
new ServerQuery("UPDATE players SET x = ?, y = ? WHERE username = ?", x, y, name);
? parameters for values. Never build SQL by joining strings that came from a client.
Parameters are sent to the database separately from the statement, which is what makes SQL injection impossible.
Table and column names cannot be parameters; keep those fixed in your code.Constructors
| Constructor | Use |
|---|---|
ServerQuery(sql, params...) | A query on its own. |
ServerQuery(connection, sql, params...) | A query made for a client; fromConnection() returns it. |
ServerQuery(utility, sql, params...)ServerQuery(utility, connection, sql, params...) | The same, attached to a DatabaseUtility, whose serverAction(query) is called before done(). |
Reading the result
| Method | Returns |
|---|---|
failed(), error() | Whether the statement could not run, and why. |
responseSize() | Number of rows a SELECT returned. |
value(field), value(row, field) | A column of the first row, or of a given row. NULL and "no such row" are Java null. |
count() | The first column of the first row as a number, for SELECT COUNT(*). |
affectedRows() | Rows changed by an INSERT, UPDATE or DELETE. |
response_getFields(), response_getValues() | All column names; all rows as a String[][]. |
getResponse(), getResponse(i), responseParamValue(i, field) | The JBend 1.x text formats, kept so old code runs unchanged. |
All values arrive as strings; convert with Integer.parseInt and friends.
Threads
done() runs on the database thread, one callback at a time. Two consequences:
- Sending to connections from
done()is fine: sends are thread-safe. - State shared with another thread (a game world the game loop also touches) needs a lock, and slow work in
done()delays every query behind it.
Answering an HTTP request from a query
See Answering after a database query: return Response.DEFERRED from the handler and call respond in done().
Creating tables
There is no migration tool. Create what you need when your code starts:
new ServerQuery("CREATE TABLE IF NOT EXISTS players (username VARCHAR(32) PRIMARY KEY, x INT NOT NULL, y INT NOT NULL)");
JBend's own tables are named with the prefix from the block (jbend_ by default). Use
Main.launcher.databaseManager().table("name") if you want your tables to follow the same prefix.
From the console
mysql info connection details and state mysql reconnect close and reopen the connection mysql SELECT COUNT(*) FROM players run a statement and print the rows