Reference/Native_modules/lu_sqlite2_SQLite_databases_object_oriented

LoadModule("lu_sqlite2") (or plugins lu_sqlite2 in server.conf) adds a real SQL database to your scripts, with SQLite 3.49.1 compiled in, so nothing else has to be installed. The whole database is one file (Data/players.db) that you can open with any SQLite tool (DB Browser for SQLite, the sqlite3 command line). It works with objects: open a SQLiteConnection, ask it questions and read the answers from a SQLiteResult, or prepare a SQLiteStatement you run many times.

Old name. Before v0.5.5 the module was called lu_db. Modules/lu_db.dll / lu_db.so are still shipped and are the same module, so LoadModule("lu_db") keeps working; load only one of the two names. It runs next to the original procedural lu_sqlite (C.5).

LoadModule("lu_sqlite2");

// created if missing; true as 2nd argument = read only
local db = SQLiteConnection("Data/players.db");
db.exec("CREATE TABLE IF NOT EXISTS players "
        + "(id INTEGER PRIMARY KEY, name TEXT UNIQUE, score INTEGER DEFAULT 0)");

// parameters: separate values, ONE array (positional) or ONE table (named)
db.exec("INSERT INTO players (name, score) VALUES (?, ?)", "Tom", 10);
db.exec("INSERT INTO players (name, score) VALUES (?, ?)", ["Ann", 20]);
local p = {}; p.n <- "Bob"; p.s <- 5;
db.exec("INSERT INTO players (name, score) VALUES (:n, :s)", p);

local res = db.query("SELECT * FROM players WHERE score > ?", 5);
while (res.next()) print(res.get("name") + " " + res.getInt("score"));

local row = db.queryRow("SELECT * FROM players WHERE id = ?", 1);   // table or null
local n   = db.queryValue("SELECT COUNT(*) FROM players");   // first column, first row

// commits; a throw inside rolls everything back
db.transaction(function(c) { c.exec("..."); c.exec("..."); });
db.close();

SQLiteConnection

SQLiteConnection (constructor)

SQLiteConnection(path [, readOnly])

Opens the database file, creating it when it does not exist (unless readOnly is true). Relative paths are relative to the server folder; the folder must exist. Throws when the file cannot be opened.

Returns: SQLiteConnection

SQLiteConnection.exec

SQLiteConnection.exec(sql, ...)

Runs a statement (CREATE, INSERT, UPDATE, DELETE, ...) and returns the number of rows it changed. Several statements separated by ; are allowed; the parameters bind to the first one.

Returns: integer

SQLiteConnection.query

SQLiteConnection.query(sql, ...)

Runs a SELECT. Every row is read at once, so nothing stays locked and you can keep the result as long as you like.

Returns: SQLiteResult

SQLiteConnection.queryRow

SQLiteConnection.queryRow(sql, ...)

The first row as a table (row.name, row.score), or null when there is none.

Returns: table / null

SQLiteConnection.queryValue

SQLiteConnection.queryValue(sql, ...)

The first column of the first row, or null. Handy for COUNT(*), MAX(...) or one field.

Returns: value / null

SQLiteConnection.prepare

SQLiteConnection.prepare(sql)

Compiles a statement once so you can run it many times with different values (faster in loops).

Returns: SQLiteStatement

SQLiteConnection.transaction

SQLiteConnection.transaction(fn)

Runs fn(connection) between BEGIN and COMMIT and returns its return value. If fn throws, everything is rolled back and the error is thrown again. Inside an already open transaction it just runs fn. Wrap bulk writes in it: 1000 INSERTs take milliseconds instead of seconds.

Returns: the return value of fn

SQLiteConnection.begin / commit / rollback / inTransaction

SQLiteConnection.begin()
SQLiteConnection.commit()
SQLiteConnection.rollback()
SQLiteConnection.inTransaction()

Manual transactions, and whether one is open.

SQLiteConnection.lastInsertId / changes / totalChanges

SQLiteConnection.lastInsertId()
SQLiteConnection.changes()
SQLiteConnection.totalChanges()

The row id of the last INSERT, the rows changed by the last statement, and the rows changed since the connection was opened.

Returns: integer

SQLiteConnection.tableExists

SQLiteConnection.tableExists(name)

true when the table exists.

Returns: bool

SQLiteConnection.errorCode / errorMessage

SQLiteConnection.errorCode()
SQLiteConnection.errorMessage()

The last SQLite error code and text (errors are also thrown, see below).

Returns: integer / string

SQLiteConnection.setBusyTimeout

SQLiteConnection.setBusyTimeout(ms)

How long to wait when another program has the file locked (default 2000 ms).

SQLiteConnection.path / isOpen / close

SQLiteConnection.path()
SQLiteConnection.isOpen()
SQLiteConnection.close()

The file path, whether it is open, and closing it. Closing finalizes its statements.

Parameters (the ... above) are separate values, or ONE array (positional, ?), or ONE table (named: key n binds :n, @n or $n). Accepted types: null, bool (stored as 1 / 0), integer (64 bit), float and string. Always use parameters instead of gluing text into the SQL; SQLiteEscape(text) only doubles single quotes and exists for the rare case you cannot.

SQLiteResult

Returned by query. Before the first next() no row is current.

SQLiteResult.next

SQLiteResult.next()

Moves to the next row; true while there is one.

Returns: bool

SQLiteResult.reset / rowCount / rows

SQLiteResult.reset()
SQLiteResult.rowCount()
SQLiteResult.rows()

Back to before the first row; the number of rows; every row as an array of tables.

Returns: - / integer / array

SQLiteStatement

Returned by prepare.

SQLiteStatement.bind / bindBlob / bindAll / clear

SQLiteStatement.bind(indexOrName, value)
SQLiteStatement.bindBlob(indexOrName, string)
SQLiteStatement.bindAll(...)
SQLiteStatement.clear()

Sets parameter values: index 1 is the first ?, or a name (":n"). bindAll takes the same arguments as exec. clear resets them all to null.

SQLiteStatement.run

SQLiteStatement.run(...)

Runs it (binding the arguments first when there are any) and returns the number of rows changed.

Returns: integer

SQLiteStatement.query

SQLiteStatement.query(...)

Runs it and returns every row as a SQLiteResult.

Returns: SQLiteResult

SQLiteStatement.step / next / reset / paramCount ...

SQLiteStatement.step()
SQLiteStatement.next()
SQLiteStatement.reset()
SQLiteStatement.paramCount()
SQLiteStatement.finalize()

Row by row access (true while there is a row), going back to the start, the number of parameters, and freeing it.

local st = db.prepare("INSERT INTO players (name, score) VALUES (?, ?)");
db.transaction(function(c) {
    for (local i = 0; i < 1000; i++) st.run("bot" + i, i);
});
st.finalize();

Reading columns

On a result and on a statement; the column is a 0 based index or a name: columnCount(), columnName(i), columns() (array of names), get(c) (integer, float, string or null as stored), getInt(c), getFloat(c), getString(c) (converted; 0 / 0.0 / "" for null), isNull(c) and row() (the current row as a table). Globals: SQLiteVersion() and SQLiteEscape(text).

Example: player accounts

LoadModule("lu_sqlite2");
local db = SQLiteConnection("Data/accounts.db");
db.exec("CREATE TABLE IF NOT EXISTS accounts "
        + "(name TEXT PRIMARY KEY, cash INTEGER, kills INTEGER, joined INTEGER)");

function onPlayerJoin(player)
{
    local acc = db.queryRow("SELECT * FROM accounts WHERE name = ?", player.Name);
    if (acc == null)
    {
        db.exec("INSERT INTO accounts VALUES (?, ?, ?, ?)", player.Name, 500, 0, time());
        player.Cash = 500;
        MessagePlayer("Welcome, new player!", player);
    }
    else
    {
        player.Cash = acc.cash;
        MessagePlayer("Welcome back, you have " + acc.kills + " kills", player);
    }
}

function onPlayerPart(player, reason)
{
    db.exec("UPDATE accounts SET cash = ? WHERE name = ?", player.Cash, player.Name);
}

function onPlayerKill(killer, player, weapon, bodypart)
{
    db.exec("UPDATE accounts SET kills = kills + 1 WHERE name = ?", killer.Name);
}

// top 5
function TopKillers()
{
    local r = db.query("SELECT name, kills FROM accounts ORDER BY kills DESC LIMIT 5");
    while (r.next()) Message(r.getString("name") + ": " + r.getInt("kills"));
}
NoteEvery failure throws a Squirrel error carrying the SQLite message (near "SELEC": syntax error, no column named ...), so use try { } catch (e) { print(e); } for SQL you build from player input. Connections still open when the scripts reload or the server stops are closed for you, and a statement of a closed connection throws. A query runs on the server thread: keep very large queries out of busy events like onPlayerUpdate. There is no path sandbox: a script can open any file the server process can, so never build the path from player text. In this Squirrel a new table key needs t.key <- value (no table literals), as in the examples.

Source code

The full source of lu_sqlite2 is on the page lu_sqlite2 source code (download as zip).

Categories: Native modules