Repository navigation
ActiveRecord Tutorial
ActiveRecord is the package of Flux that talks to the database. With it a plugin describes its tables in Lua, loads rows as Lua objects and writes them back, without writing SQL. This page takes you from an empty plugin to one that creates its own tables, stores and loads rows, and changes two rows at once safely. It assumes that you write Garry's Mod Lua and know what a Flux plugin is. It does not assume that you have used a database beyond a simple SELECT.
Read it top to bottom once; it takes about half an hour. Every section builds on the one before, and the cheat sheet at the end is there for when you come back.
- What you will build
- Before you start
- Where the database is configured
- Migrations
- Models
- Creating a record
- Finding records
- Results arrive in a callback
- Changing and deleting a record
- Conditions and ordering
- Relations and preload
- Validations
- One row per key
- Many rows at once
- Transactions
- When a query fails
- Loading when the server starts
- What the package does not do
- Differences between the databases
- Common mistakes
- Cheat sheet
A plugin called Bounties. A character can put a price on the head of another character, other characters can add to the reward, and a hunter can claim it. The plugin stores two kinds of things:
| Table | One row is | Columns you add |
|---|---|---|
bounties |
a bounty on a character |
character_id, reason, reward, hunter_id, later expires_at
|
bounty_pledges |
what one character has added to one bounty |
bounty_id, character_id, amount
|
There is no menu and no command on this page. The plugin is a handful of functions and hooks that print to the server console, so that nothing distracts from the database.
You need a schema that runs on Flux, with the server in the development environment. In that environment the server console shows every statement that ActiveRecord sends to the database together with its values, which is the best way to see what your code does.
Create the plugin in the plugins folder of your schema. fpkg new plugin bounties, run in the schema folder, writes a skeleton; these are the files the plugin ends up with:
| File | What it holds |
|---|---|
plugins/bounties/plugin.yml |
name, description and what the plugin depends on |
plugins/bounties/plugin/sh_plugin.lua |
the main file |
plugins/bounties/plugin/sv_plugin.lua |
the functions of the plugin |
plugins/bounties/plugin/sv_hooks.lua |
the hook handlers |
plugins/bounties/plugin/migrations/ |
the files that create and change the tables |
plugins/bounties/plugin/models/ |
one file per table |
plugins/bounties/plugin/languages/en.yml |
the one phrase the plugin shows to a player |
The plugin refers to characters, so it depends on the Characters plugin:
name: "Bounties"
description: "Lets characters put a price on the head of another character."
author: "You"
depends:
- charactersPLUGIN:set_global('Bounties')
require_relative 'sv_plugin'
require_relative 'sv_hooks'Two things to know before the first query:
-
The database exists on the server only. Model files are shared, but on the client the methods that need the database do nothing. Everything on this page belongs in
sv_files. -
You can try every sample from the server console. Put a sample into a file in your schema folder, for example
try.lua, and runlua_run include('<your_schema>/try.lua'). The samples use the characters with the ids 1, 2 and 3, so create a few characters in the game first.
Flux reads the connection from gamemodes/<your_schema>/config/database.yml. If the file is not there, the one that ships with Flux is used, and that one selects SQLite, which needs no setup. To use another database, copy gamemodes/<your_schema>/packages/flux/config/database.yml into the config folder of your schema and edit the copy. The copy may also be named database.local.yml.
The file has one section per environment, and the server reads the section that is named after the environment it runs in. These are the lines of a section that you change; leave the others as they are in the copy:
development:
adapter: "pg"
host: "127.0.0.1"
user: "flux"
password: "secret"
database: "flux_dev"
port: ~The adapter is the part of ActiveRecord that speaks to one kind of database. There are three:
adapter |
Database | How a query runs |
|---|---|---|
sqlite |
a file, garrysmod/sv.db, on the disk of the server |
at once, while the server waits for it |
mysqloo (also mysql, mariadb) |
a MySQL or MariaDB server | in the background |
pg (also postgres, postgresql) |
a PostgreSQL server, version 14 or newer | in the background |
port: ~ means the default port of the adapter. The section also has a pool setting, which matters for transactions and is ignored by SQLite; the comments in the file explain the rest. On MySQL and PostgreSQL the database itself has to exist before the server starts.
When the server has connected, its console says which database it uses and where that was set, for example: ActiveRecord - Connected to database 'flux' on mariadb:3306 through the mysqloo adapter, as set in the 'development' section of gamemodes/hl2rp/config/database.local.yml.
SQLite is fine for development and for looking around. The difference in the last column of the table is the most important thing on this page, and Results arrive in a callback explains it. Whatever you develop on, run your plugin at least once on the kind of database your server will use.
A migration is a small Lua file that describes one change to the structure of the database: a new table, a new column, a new index. Flux remembers which migrations a database has run, and runs each one exactly once. That is why a table is never created by hand: every server that installs your plugin gets the same tables, in the same order, by starting up.
A migration file lives in the migrations folder of the plugin and is named <version>_<name>.lua. The version is a timestamp in the form YYYYMMDDHHMMSS; use the current date and time. Migrations run in the order of their versions, and the current time is always later than the migrations your table builds on. The name has to be unique in the whole schema, so name it after what it does to which table.
plugins/bounties/plugin/migrations/20261203120000_create_bounties.lua:
local CreateBounties = ActiveRecord.Migration.new()
--- Creates the bounties table.
function CreateBounties:change()
create_table('bounties', function(t)
t:references('character', { null = false, foreign_key = { on_delete = 'cascade' } })
t:string { 'reason', null = false }
t:bigint { 'reward', null = false, default = 0 }
t:integer 'hunter_id'
t:timestamps()
end)
end
return CreateBountiesLine by line:
-
create_tablecreates the table. It adds anidcolumn on its own: a number that the database gives to each new row and that identifies the row from then on. -
t:references('character', ...)adds acharacter_idcolumn that points at a row of thecharacterstable, and an index on it.foreign_keyadds a foreign key: a rule, kept by the database, that the value must be the id of a character that exists.on_delete = 'cascade'tells the database to delete the bounties of a character when the character is deleted. -
t:string { 'reason', null = false }adds a text column.null = falsemeans that every row must have a value for it. The column name comes first, the options after it. -
t:bigint { 'reward', null = false, default = 0 }adds a whole number that can get large.defaultis the value of a row that gives none. -
t:integer 'hunter_id'adds a number that may be empty. It will hold the character who claimed the bounty, and stays empty while the bounty is open. -
t:timestamps()addscreated_atandupdated_at, which ActiveRecord fills in for you.
The column types:
| Type | Holds | In Lua you get |
|---|---|---|
string, text
|
short text, long text | a string |
integer, bigint
|
whole numbers; bigint for large ones such as money |
a number |
float, decimal
|
numbers with a fraction | a number |
boolean |
true or false | a boolean |
datetime, timestamp, date, time
|
a moment or a part of one | a string; time_from_timestamp(text) turns it into a Unix time, to_datetime(unix_time) goes the other way |
json |
a Lua table, stored as text | the table |
binary |
raw bytes | a string |
A default goes into the SQL as it is written. Numbers and booleans are plain Lua values (default = 0); a text default keeps its SQL quotes (default = "'open'").
Restart the server. When it starts, Flux copies the new migrations of every plugin into gamemodes/<your_schema>/db/migrate/ and runs the ones the database has not run yet. The console says so:
Installed migration <your_schema>/db/migrate/20261203120000_create_bounties.bounties.lua (from <your_schema>/plugins/bounties/plugin/migrations/20261203120000_create_bounties.lua)== 20261203120000 CreateBounties: migrated (0.0021s) ==
The same can be done from a shell in the schema folder, without the server:
fpkg db:migrate
fpkg db:migrate:statusInside the folder of a server (garrysmod/gamemodes/<your_schema>) fpkg works on the database of that server. In a copy of the schema outside of a server it uses a SQLite file of its own, so there it only shows whether your migration runs. db:migrate:status lists every migration as up (it has run) or down (it has not). In the server console the same tasks are called flux db:migrate:status, flux db:migrate and so on; flux alone lists them. One limit: flux db:migrate in the console of a running server runs the migrations that are already installed. A file that you have just added to a plugin is only installed at the next start of the server, or by fpkg.
The whole db folder of the schema is generated. Do not edit it; edit the file in your plugin.
A migration that has run is not run again. If you edit its file afterward, the copy in db/migrate is updated and the table stays as it was. To change a table, write a new migration. Bounties should be able to expire, so add a column:
plugins/bounties/plugin/migrations/20261203120200_add_expires_at_to_bounties.lua:
local AddExpiresAtToBounties = ActiveRecord.Migration.new()
--- Adds the time a bounty expires at.
function AddExpiresAtToBounties:change()
add_column('bounties', 'expires_at', 'datetime')
end
return AddExpiresAtToBountiesRestart the server and the column is there, empty for the rows that exist.
Because the function is called change, Flux can also undo it: it knows that the opposite of create_table is dropping the table and that the opposite of add_column is removing the column. db:rollback reverts the newest migration that has run, and db:migrate:redo reverts it and runs it again. While you are still designing a table that only your development database has, and your migration is the newest one, that is the way to try an edit: change the file, then run fpkg db:migrate:redo. It drops what the migration created, including the rows.
There is also a generator, fpkg generate migration AddExpiresAtToBounties expires_at:datetime. It writes its file into db/migrate of the schema, not into a plugin, so for a plugin write the file by hand as above.
A model is a Lua class that stands for one table. A record is one object of that class, and it stands for one row: the columns of the row are the fields of the object.
plugins/bounties/plugin/models/bounty.lua:
class 'Bounty' extends 'ActiveRecord::Base'That is the whole model. Flux loads every file in models, and the class finds its table by its own name: the table is the plural of the class name, in lowercase with underscores. Bounty uses bounties; BountyPledge, which comes later, uses bounty_pledges. The class is a global, so every server file of your plugin can use Bounty from now on.
local bounty = Bounty.new()
bounty.character_id = 1
bounty.reason = 'Stole a can of water'
bounty.reward = 200
bounty:save(function(success, error_text)
if !success then
print('The bounty could not be saved: '..error_text)
return
end
print('Saved as bounty #'..bounty.id)
end)Bounty.new() (with a dot) makes a record that exists in Lua only. save writes it: a record that is not in the database yet is inserted, one that was loaded or saved before is updated. The function you pass to save is called when the database has answered, with true, or with false and the reason. After a successful insert the record has its id, its created_at and updated_at, and the defaults of the columns you gave no value for. The callback is optional.
If the save fails with a message about a foreign key, there is no character with that id. That is the rule from the migration at work.
In a plugin you wrap this in a function. Add it to sv_plugin.lua:
--- Puts a bounty on a character.
-- @param character_id [Number the character the bounty is on]
-- @param reason [String]
-- @param reward [Number]
-- @param callback [Function called with the bounty once it is saved, or with nil and the error
-- text]
function Bounties:post(character_id, reason, reward, callback)
local bounty = Bounty.new()
bounty.character_id = character_id
bounty.reason = reason
bounty.reward = reward
bounty:save(function(success, error_text)
if !success then
callback(nil, error_text)
return
end
callback(bounty)
end)
endNote that post does not return the bounty. It cannot, and the section after the next one explains why.
A query is written in three steps: say which rows you want, say what to do with them, and send it.
Bounty:find(12):expect(function(bounty)
if !bounty then
print('There is no bounty #12')
return
end
print(bounty.reason..' pays '..bounty.reward)
end):load()Bounty:where('character_id', 1):get(function(bounties)
for _, bounty in ipairs(bounties) do
print('#'..bounty.id, bounty.reason, bounty.reward)
end
end):load()-
Which rows.
find(id)is the row with that id.where(column, value)is every row in which the column has that value. More ways follow in Conditions and ordering. -
What to do with them.
expectis for one record: its function gets the first record that matches, ornilwhen there is none.getis for a list: its function gets a list of records, which is empty when there is none. -
Send it.
load()sends the query. Without it nothing happens at all: no query, no callback, no error.
Some shortcuts: Bounty:find_by('reason', text) is the first row with that value in the column, Bounty:first() and Bounty:last() are the rows with the lowest and the highest id, and Bounty:all() is every row, ordered by id. find and find_by also take the expect function as their last argument, as in Bounty:find(12, function(bounty) ... end):load(). All of them still need load().
Every column also has a finder of its own, named find_by_ and the column:
Bounty:find_by_character_id(1, function(bounty)
print(bounty and bounty.reason or 'There is no bounty on character 1')
end):load()Bounty:find_by_character_id(1, ...) is Bounty:find_by('character_id', 1, ...): one record, the first that matches, or nil, and it needs load() like the others. The model gets these finders as soon as the server knows its table: when it has read the database at startup, after a migration, and when a code refresh defines the model again. Until the first of these they are missing, while find_by works at any time.
Every query builds new objects. If you load bounty 12 twice, you hold two different Lua tables that stand for the same row, and a change to one does not show in the other.
A callback is a function that you hand over to be called later. Every query on this page takes one, and nothing returns a result directly. The reason is in the table of adapters above: on MySQL and PostgreSQL a query runs in the background. The server sends it and goes on with the next line of your code, the next tick, the next player. The answer arrives a moment later, and that is when your function is called. If the server waited instead, every player would freeze for the length of every query.
Run this:
print('1: before the query')
Bounty:where('character_id', 1):get(function(bounties)
print('the callback, with '..#bounties..' bounties')
end):load()
print('2: after the query')On PostgreSQL and MySQL it prints 1, then 2, then the callback. On SQLite it prints 1, the callback, then 2, because SQLite answers at once.
Warning
Code that uses a result outside of its callback works on SQLite and breaks on PostgreSQL and MySQL. Write for the database that answers later, and the code is right on all three.
What this means for your code:
Everything that needs the result goes inside the callback. count asks the database how many rows match and calls its function with the number; it is sent at once and needs no load(). This function returns the right number on SQLite and always 0 on a database server, because return count runs before the callback has set it:
--- Returns the number of bounties on a character.
-- @param character_id [Number]
-- @return [Number]
function Bounties:count_on(character_id)
local count = 0
Bounty:where('character_id', character_id):count(function(amount)
count = amount
end)
return count
endA function that needs the database takes a callback itself. That is the fix, and it is the reason Bounties:post above has a callback parameter:
--- Counts the bounties on a character.
-- @param character_id [Number]
-- @param callback [Function called with the number of bounties]
function Bounties:count_on(character_id, callback)
Bounty:where('character_id', character_id):count(function(amount)
callback(amount)
end)
endThe same is true for save. Right after bounty:save() the record of a new row has no id yet on a database server. If the next step needs the id, put that step into the callback of save.
The world may have changed when the callback runs. A player can leave between the query and its answer. Check what you are about to use.
The last point is how you load something for a player. The Characters plugin runs the PostLoadCharacter hook when a player has loaded a character. Add a handler to sv_hooks.lua that tells the player about the bounties on that character:
--- Tells a player how many bounties are on the character they have loaded.
-- @param owner [Player]
-- @param character [Character]
function Bounties:PostLoadCharacter(owner, character)
Bounty:where('character_id', character.id):count(function(amount)
if !IsValid(owner) or amount == 0 then return end
owner:notify('notification.bounties.wanted', { count = amount })
end)
enden:
notification:
bounties:
wanted: "There are {count} bounties on your head."Note
A MySQL server delivers its answers while the game server is thinking, and an empty server sleeps. If you try the samples from the console of an empty server on MySQL, the callbacks do not arrive until the server wakes up. Run sv_hibernate_think 1 in the console to get them at once.
To change a row, change the fields of its record and save it:
--- Marks a bounty as claimed by a character.
-- @param bounty [Bounty]
-- @param hunter_id [Number the character who claims it]
-- @param callback [Function called with true once the row is written, or with false and the
-- error text]
function Bounties:claim(bounty, hunter_id, callback)
bounty.hunter_id = hunter_id
bounty:save(function(success, error_text)
if !success then
bounty.hunter_id = nil
end
callback(success, error_text)
end)
endThree things about save that are worth knowing early:
-
It writes only the columns you changed. A record remembers what the row held when it was loaded or last written, and a save sends the columns that differ from that, a table in a JSON column that you changed in place included. When nothing differs, no statement is sent and the save is over right away: a valid record gets its callback with
truebeforesavereturns, on every database. Only if an earlier save of the same record has not been answered yet does the callback wait for that answer and report it. - A record does not see what others write to its row. Two records of the same row each write their own changes and keep showing their own old values for the rest. Keep one record per row where you can.
-
It writes only columns. A field that is not a column of the table is ignored without a word. If
bounty.hunter = 3seems to save and nothing changes, look for the typo. -
The record in Lua is yours to keep right.
claimsetshunter_idbefore the database has agreed, so it puts the old value back when the save fails.
Setting a field to nil and saving empties the column. updated_at moves on its own when a save changes something.
To delete a row, call destroy on its record:
bounty:destroy(function(success, error_text)
if !success then
print('The bounty could not be deleted: '..error_text)
end
end)destroy deletes this one row. Rows of other tables that point at it are deleted by the database when their foreign key says on_delete = 'cascade', and only then. A record that has been destroyed cannot be saved again.
where takes several forms. In all of them the values travel to the database separately from the SQL, so text that a player typed can be passed as it is. Never build a condition by joining strings with ...
| You write | It matches rows where |
|---|---|
where('character_id', 1) |
the column equals the value |
where('reward >= ?', 100) |
the SQL condition is true; each ? is replaced by the next value |
where('reward >= ? AND reward < ?', 100, 400) |
the same, with two values |
where({ character_id = 1, hunter_id = ActiveRecord.null }) |
every column of the map matches |
where({ character_id = { 1, 2 } }) |
the column equals one value of the list |
where('hunter_id', nil) |
the column is empty |
where_not('character_id', 1) |
the condition is not true |
where(...):where(...) |
both conditions are true |
Rows come back in no particular order unless you ask for one. order(column) sorts ascending, order(column, 'desc') descending; the direction is written in lowercase. limit(n) keeps the first n rows and skip(n) leaves n out before that. The ten highest open bounties:
Bounty:where('hunter_id', nil):order('reward', 'desc'):limit(10):get(function(bounties)
for place, bounty in ipairs(bounties) do
print(place..'. '..bounty.reason..' ('..bounty.reward..')')
end
end):load()NULL is what a database calls "no value". The hunter_id of an open bounty is NULL. In Lua a NULL column reads as nil, and writing nil to a field and saving makes the column NULL again.
There is one place where nil cannot do the job: inside a Lua table, because a table cannot hold nil. { hunter_id = nil } is simply an empty table. For that case there is ActiveRecord.null, a value that stands for NULL wherever a table is involved:
Bounty:where({ character_id = 1, hunter_id = ActiveRecord.null }):get(function(bounties)
print(#bounties..' open bounties on character 1')
end):load()With it the hook handler from the last section can count only the open bounties: replace its where('character_id', character.id) with where({ character_id = character.id, hunter_id = ActiveRecord.null }).
Two consequences:
- A
nilin a condition map removes that condition, and the query matches more rows than you meant. Lua does not keep a key whose value isnil, so ActiveRecord cannot notice it; only a map that ends up with no keys at all raises an error.where({ character_id = some_id, hunter_id = ActiveRecord.null })with asome_idthat isnilmatches the open bounties of every character. Check an id before you put it into a map. - NULL is not smaller, larger or equal to anything.
where('expires_at < ?', to_datetime(os.time()))finds the bounties that have expired and leaves out the ones without an expiry time, which is what you want here; in other cases it is a surprise.
A relation tells ActiveRecord how two tables belong together, so that it can load the rows of one along with the rows of the other.
Other characters add to the reward of a bounty. Each of them gets one row per bounty that says how much they have put in.
plugins/bounties/plugin/migrations/20261203120100_create_bounty_pledges.lua:
local CreateBountyPledges = ActiveRecord.Migration.new()
--- Creates the bounty_pledges table.
function CreateBountyPledges:change()
create_table('bounty_pledges', function(t)
t:references('bounty', { null = false, index = false, foreign_key = { on_delete = 'cascade' } })
t:references('character', { null = false, foreign_key = { on_delete = 'cascade' } })
t:bigint { 'amount', null = false, default = 0 }
t:timestamps()
end)
add_index('bounty_pledges', { 'bounty_id', 'character_id' }, { unique = true })
end
return CreateBountyPledgesThe new part is add_index with unique = true. An index lets the database find rows by those columns quickly. A unique index also makes the database refuse a second row with the same values: one pledge per character per bounty, guaranteed by the database and not by your code. You will need that in One row per key. The first references says index = false because the unique index already starts with bounty_id.
plugins/bounties/plugin/models/bounty_pledge.lua:
class 'BountyPledge' extends 'ActiveRecord::Base'
BountyPledge:belongs_to 'Bounty'
BountyPledge:belongs_to 'Character'And in models/bounty.lua:
class 'Bounty' extends 'ActiveRecord::Base'
Bounty:belongs_to 'Character'
Bounty:has_many 'bounty_pledges'| Declaration | Takes | Column it uses | Field it fills |
|---|---|---|---|
Bounty:belongs_to 'Character' |
the name of the other model |
character_id of bounties
|
bounty.character, one record |
Bounty:has_many 'bounty_pledges' |
the name of the other table |
bounty_id of bounty_pledges
|
bounty.bounty_pledges, a list |
belongs_to always uses the column named after the model, <model>_id. That is why hunter_id is a plain number here and not a relation: to load the hunter, use Character:find(bounty.hunter_id).
Relations are loaded only when you ask for them. A plain query loads the rows of its own table and nothing else:
Bounty:find(12):expect(function(bounty)
print(bounty.bounty_pledges, bounty.character)
end):load()This prints nil nil. Name the relations with preload and they are there:
Bounty:find(12):preload('bounty_pledges', 'character'):expect(function(bounty)
if !bounty then return end
print(bounty.character.name..' is wanted for '..bounty.reason)
for _, pledge in ipairs(bounty.bounty_pledges) do
print(' character #'..pledge.character_id..' has pledged '..pledge.amount)
end
end):load()The rule exists because loading is not free. Each relation costs one more query, for all the records of the result together and not one per record, and most code needs none of them. So you say what you need, and a field that is nil tells you that it was not loaded. A has_many that was loaded and has no rows is an empty list, not nil.
Relations of relations are named in a table under their parent:
Bounty:where('hunter_id', nil):preload({ bounty_pledges = { 'character' } }):get(function(bounties)
for _, bounty in ipairs(bounties) do
for _, pledge in ipairs(bounty.bounty_pledges) do
print(pledge.character.name..' has pledged '..pledge.amount..' to bounty #'..bounty.id)
end
end
end):load()For a record that you already hold, bounty:load_relations('bounty_pledges', function() ... end) loads the relation and then calls the function. A name that is not a relation of the model is a Lua error at the preload call, such as Bounty has no relation named 'pledges'.
save also saves the records of the has_many relations that are loaded on the record. A relation that was not loaded is left alone. This is convenient: a new bounty and its first pledge can be written with one call, and the pledge gets the id of the bounty by itself.
local bounty = Bounty.new()
bounty.character_id = 3
bounty.reason = 'Hoarding rations'
bounty.reward = 10
local pledge = BountyPledge.new()
pledge.character_id = 1
pledge.amount = 10
table.insert(bounty.bounty_pledges, pledge)
bounty:save()Warning
It also means that a loaded child stays in Lua for as long as its parent does, with the values it had when it was loaded. If other code changes that row through another record, the child does not learn of it: the save of the parent sends nothing for it, because the child itself has not changed, but whoever reads the child reads old values, and a column that is changed on it later is written over the newer row. Preload onto a long-lived record only the rows that nothing else changes.
The Characters plugin loads the characters of a player when the player joins, and lets plugins name relations to load with them. A plugin whose rows belong to a character and are changed only through that character does this:
Character:has_many 'bounties'--- Loads the bounties on a character together with the character.
-- @param preloads [Map relations of the characters, changed in place]
function Bounties:AdjustCharacterPreloads(preloads)
preloads[#preloads + 1] = 'bounties'
endThe first line goes into a file of its own in models, for example models/character.lua; the handler goes into sv_hooks.lua. From then on the characters of a player who joins have their bounties list.
The Bounties plugin does not do this, because of the warning above. A character stays loaded for as long as its player is on the server and is saved again and again, while other players raise and claim the bounties on it. The copies on the character would overwrite their changes. Bounties are loaded when they are needed, as the hook handler in Results arrive in a callback does. Use the preload for things like notes or skills, which only the character's own code changes.
A validation is a check that a record must pass before save sends anything. Add these to models/bounty.lua:
Bounty:validates('character_id', { presence = true })
Bounty:validates('reason', { presence = true, length = { maximum = 120 } })
Bounty:validates('reward', { numericality = { only_integer = true, greater_than_or_equal_to = 0 } })A record that fails is not written. The callback of save gets false and a text such as reason failed the presence validation, and the console prints which model and column failed. Inside a transaction it also makes the transaction roll back.
The validations of a column run one after another, and the first that fails is the one reported. Their order is fixed, whatever order you write them in: presence and absence, then length, min_length, max_length, numericality, comparison, inclusion, exclusion, format and uniqueness, then your own in the order in which they were added. A missing reason is therefore always reported as presence. The columns are checked in the order of their first validates call.
| Validation | The record passes when | Example |
|---|---|---|
presence = true |
the field is not nil
|
validates('reason', { presence = true }) |
absence = true |
the field is nil
|
validates('hunter_id', { absence = true }) on a model whose rows must leave it empty |
length = { minimum = a, maximum = b }, also is = n and within = { a, b }
|
the text has that many characters, a list that many elements; nil counts as 0 |
validates('reason', { length = { within = { 3, 120 } } }) |
min_length = n, max_length = n
|
the same as length with one bound |
validates('reason', { min_length = 3 }) |
numericality = true, or a table of conditions: only_integer, greater_than, greater_than_or_equal_to, equal_to, less_than, less_than_or_equal_to, other_than, odd, even, within
|
the field is a number, or text of a decimal number such as '12' or '-1.5' (no spaces around it, no hexadecimal), and meets every condition; with only_integer text must be digits |
validates('reward', { numericality = { only_integer = true, greater_than = 0 } }) |
comparison, with the keys of the comparisons of numericality
|
the field compares so with another column (named by a string), with what a function returns, or with a value; date and time columns compare as times, and the created_at and updated_at of a record that is not saved yet count as the current time; another nil on either side fails |
validates('expires_at', { comparison = { greater_than = 'created_at' }, allow_nil = true }) |
inclusion = { ... } |
the field is one of the list | validates('reward', { inclusion = { 100, 200, 500 } }) |
exclusion = { ... } |
the field is none of the list | validates('reason', { exclusion = { 'none', 'test' } }) |
format = pattern, or { with = pattern, without = pattern }
|
the field, as text, matches the Lua pattern with and not the pattern without; a pattern matches anywhere unless it starts with ^ and ends with $; nil fails |
validates('reason', { format = { without = '[<>]' } }) |
uniqueness = true, or { case_sensitive = true }
|
no other row holds the same value; case is ignored unless case_sensitive is true; nil passes |
validates('reason', { uniqueness = true }) |
Every validation takes two more settings. allow_nil = true lets a field that is nil pass it, and message is the text that the callback of save gets instead of the generated one. Put them into the table of one validation, or next to the validations to apply them to all of them:
Bounty:validates('hunter_id', {
comparison = { other_than = 'character_id' },
allow_nil = true,
message = 'A character cannot claim the bounty on itself'
})A validation or an option with a misspelled name, or a setting of the wrong shape such as length = 120, is a Lua error at the validates line, so it shows when the model loads and not at the first save.
uniqueness asks the database before the row is written. Two saves at the same moment, or on two servers, can both pass it, so it does not keep duplicates out. Only a unique index does that: use uniqueness for the message and the index for the guarantee.
You can add your own. A validator is a function that calls one of the two functions it is given. The optional function after it gets the setting of a validates call and returns an error text when the setting has the wrong shape:
ActiveRecord.Validator:add('multiple_of', function(record, column, step, _options, pass, fail)
if isnumber(record[column]) and record[column] % step == 0 then
pass(record)
else
fail(record, column, 'multiple_of')
end
end, function(step)
if !isnumber(step) then return 'takes a number' end
end)
Bounty:validates('reward', { multiple_of = 10 })Mind the limits. Validations run in Lua when save is called; they are not rules of the database. They run before the defaults of the table apply, so with the validations above a bounty must be given its reward. And the methods that write without a record, upsert, update_all and their relatives, skip them. What must hold no matter how a row is written belongs into the migration: null = false, a foreign key, a unique index, or a check constraint.
A model can also define methods that save calls along the way: before_save, before_create, after_create and after_save, and restored, which runs for a record that has been loaded.
A check constraint is a condition that the database tests on every row it writes, whoever writes it. A bounty must never pay a negative reward, not even when update_all sets it:
plugins/bounties/plugin/migrations/20261203120300_add_reward_check_to_bounties.lua:
local AddRewardCheckToBounties = ActiveRecord.Migration.new()
--- Keeps the reward of a bounty from going below zero.
function AddRewardCheckToBounties:change()
add_check_constraint('bounties', 'reward >= 0', { name = 'bounties_reward_not_negative' })
end
return AddRewardCheckToBountiesThe condition is SQL, written as after a WHERE, about the columns of the same row. Without a name the constraint is named after the table and the condition, the same on every database. A name belongs to one constraint of the whole database, so giving the same name to a constraint on another table is an error. db:rollback removes it again, and a table that is created with create_table takes its constraints there: t:check_constraint('reward >= 0'). If rows that break the rule are already there, the migration fails and the constraint is not added. MySQL enforces check constraints from version 8.0.16 and can remove one from 8.0.19; MariaDB does both from 10.2.1. The two other rules of a column have migration methods of their own: change_column_null('bounties', 'reason', true) lets the reason be empty, and change_column_default('bounties', 'reward', { from = 0, to = 10 }) changes the default reward.
A write that breaks the rule is refused by the database and reaches your code like any failed statement: save calls back with false, update_all and upsert call their error function, and a transaction rolls back. The error text names the constraint, in the words of the database: CHECK constraint failed: bounties_reward_not_negative on SQLite, new row for relation "bounties" violates check constraint "bounties_reward_not_negative" on PostgreSQL. Do not show that text to a player. Check the value in Lua first and tell the player with a phrase of your plugin; the constraint is there for the code that skips that check.
Often a table holds at most one row for some key: one pledge per character and bounty, one setting per name. The naive way is to look for the row and then either update it or create it. upsert does it in one statement: it inserts the row, or updates the row that is already there. The word is short for "update or insert".
BountyPledge:upsert({ bounty_id = 12, character_id = 2, amount = 40 },
{ unique_by = { 'bounty_id', 'character_id' } }, function()
print('The pledge is written')
end, function(error_text)
print('The pledge could not be written: '..error_text)
end)Run it twice with different amounts and there is still one row, with the second amount. unique_by names the columns of the unique index that decides whether "the row is already there"; the table must have that index, which is why the migration created it.
What to know about upsert:
- It writes a row, not a record. No object is made, no validations run,
created_atandupdated_atare still filled in. - It replaces values. To add to the amount that is there you have to read it first, which is what the next method and the transaction below are for.
- The function gets the list of written rows with their
idon PostgreSQL and MariaDB. On the SQLite that is built into the game the list is empty. Do not build on it; passreturning = falseamong the options when you do not need it. - On MySQL the row that gets updated is the one that collides on any unique index, whatever
unique_bysays. Give such a table one unique index besides the id.
When you want the record, use find_or_create_by. It finds the first row with these values or creates one, and hands you the record either way:
BountyPledge:find_or_create_by({ bounty_id = 12, character_id = 3 }, function(pledge)
pledge.amount = pledge.amount + 15
pledge:save()
end, function(error_text)
print('The pledge could not be loaded: '..error_text)
end)It is two statements, a query and then perhaps an insert. On a database that several servers share, another server can insert the same row in between; the unique index then refuses the second insert and the error function is called. create_or_find_by takes the same arguments and goes the other way around, insert first and find on a collision, for the cases where that matters.
update_all and delete_all change or delete every row that the conditions before them match, with one statement and without loading anything.
A hunter brings in a character and claims every open bounty on it:
Bounty:where({ character_id = 1, hunter_id = ActiveRecord.null }):update_all({ hunter_id = 3 }, function(count)
print(count..' bounties claimed')
end, function(error_text)
print('The bounties could not be claimed: '..error_text)
end)The expired bounties are removed:
Bounty:where('expires_at < ?', to_datetime(os.time())):delete_all(function(count)
print(count..' expired bounties deleted')
end, function(error_text)
print('The expired bounties could not be deleted: '..error_text)
end)Both take a function that gets the number of rows, and a second one for a failure. In the map of update_all, ActiveRecord.null empties a column.
They are fast because they skip everything else: no records are made, no validations run, updated_at does not move, and records of those rows that you hold in Lua do not learn of the change. They do not take limit or skip; a chain that has one raises an error.
count belongs to the same family. It counts the rows that the conditions before it match, with one SELECT COUNT(*), and loads none of them:
Bounty:where({ character_id = 1, hunter_id = ActiveRecord.null }):count(function(amount)
print(amount..' open bounties on character 1')
end, function(error_text)
print('The bounties could not be counted: '..error_text)
end)Its function gets a number, 0 when no row matches. It is sent at once, without load(), follows the same rules as update_all (no limit or skip, an order is left out) and, without a where, counts every row of the table.
Warning
Without a where in front, delete_all deletes every row of the table and update_all changes every row.
Raising a bounty changes two rows: the pledge of the character who pays, and the reward of the bounty. If the first is written and the second fails, the numbers no longer add up, and nothing in the database shows which one is wrong.
A transaction is a group of statements that the database treats as one. Either all of them take effect, which is called a commit, or none of them does, which is called a rollback. There is no state in between, not even if the server crashes halfway.
Add this to sv_plugin.lua:
--- Adds an amount to what a character has pledged to a bounty and to the reward of the bounty,
-- both or neither.
-- @param bounty [Bounty]
-- @param character_id [Number the character who pledges]
-- @param amount [Number]
-- @param callback [Function called with true once both rows are written, or with false and
-- the error text]
function Bounties:raise(bounty, character_id, amount, callback)
Bounty:transaction(function(transaction)
bounty.reward += amount
transaction:after_commit(function()
callback(true)
end)
transaction:after_rollback(function(error_text)
bounty.reward -= amount
callback(false, error_text)
end)
bounty:save()
BountyPledge:find_or_create_by({ bounty_id = bounty.id, character_id = character_id }, function(pledge)
pledge.amount += amount
pledge:save()
end)
end)
endBounty:transaction runs the function you give it. Every statement that the function issues, here two saves and the query and insert of find_or_create_by, belongs to the transaction. When the function ends, the transaction commits. If one of the statements failed, it rolls back instead: the statements after the failed one are not even sent, and what the earlier ones did is undone. A save that is refused, for example by a validation, and an error raised in the callback of a statement count as failures too.
The function attaches what should happen for either outcome to the transaction object it is given. after_commit functions run once everything is written. after_rollback functions run when nothing is, with the error text. There is one rare exception: when the connection is lost during the commit itself and the database cannot be asked what became of it, the transaction is reported as rolled back although the database may have kept it, and the console names the rows concerned. Tell a player that it worked in after_commit and nowhere else.
The order inside raise is deliberate:
- Change the records in Lua.
- Attach the callbacks. An error raised further down ends the function on the spot; callbacks that were to be attached after that line would never be attached.
- Issue the statements.
Statements wait inside a transaction. The rule from Results arrive in a callback is suspended here. Inside the function every statement is sent and answered before the next line runs, on every database, so the callback of find_or_create_by has run and has saved the pledge before the function ends. This is what makes it possible to use the result of one statement in the next. It also means that the game server waits for the database while the transaction runs.
A transaction holds the server for a few milliseconds. In the tests for this page raise held the server for 2 to 4 ms on PostgreSQL and on MariaDB running on the same machine, and for 9 to 12 ms the first time or two after a start. In development the console prints the time after every transaction on a database server. The time grows with every statement and with the distance to the database. So keep transactions short: only the statements that must succeed together, no loops over many rows, and never one per tick or per player in a loop. An action a player can repeat quickly, such as buying something, deserves a cooldown.
The pool. On PostgreSQL and MySQL the server keeps several connections to the database, at most pool of database.yml (5 unless you change it, never fewer than 2). One of them carries the ordinary statements, one after another. A transaction borrows one of the others for as long as it runs, so it does not have to queue behind the statements that are already on their way. It only waits for earlier statements that concern the same table or record. If no connection can be had, the transaction fails at once: nothing is sent and the after_rollback functions run with the reason. A transaction also never waits without a limit: when a statement of it has to wait longer than transaction_timeout of database.yml (2 seconds unless you change it) for earlier statements or for a row that something else has locked, the transaction rolls back. Every server that shares the database opens up to pool connections of its own, and the database has to allow that many. SQLite has one connection and nothing to set.
What a rollback does not undo. The database goes back; your Lua values do not. A record that was inserted in the transaction loses its id again and one that was destroyed can be saved again, but a field you changed keeps its new value. That is why raise subtracts the amount again in after_rollback.
What causes a rollback. A statement that fails, a save that is refused before anything is sent (its validation fails, or the record was destroyed), and an error raised in the transaction function or in the callback of one of its statements, which is printed. The save that was refused still gets false and the reason in its own callback. To abandon a transaction on purpose, raise an error with error() in the transaction function itself: it is printed, the transaction rolls back, and the after_rollback functions that were attached before that line run.
Bounty:transaction returns true when it has committed, or false and the error text. You rarely need that, and you should not rely on it in a function that others call: a transaction opened inside another one joins it, its outcome is that of the outer one, and it is only known when the outer one ends. The two callbacks are right in both cases. ActiveRecord.transaction(function(transaction) ... end) is the same thing without a model in front; which model you call it on makes no difference.
Queries fail: the database is restarting, a foreign key refuses a row, a condition has a typo. ActiveRecord always prints a failed statement to the console, with the statement and the error of the database. What your code learns depends on what you called:
| You called | A failure reaches you through |
|---|---|
a query with expect, get or rescue
|
the function given to on_error, which is added before load(); without it none of your functions is called |
save, destroy
|
the callback: false and the error text |
update_all, delete_all, count, upsert, find_or_create_by
|
the last argument, a function that gets the error text |
| a statement inside a transaction | the after_rollback functions of the transaction |
Bounty:where('character_id', 1):get(function(bounties)
print(#bounties..' bounties')
end):on_error(function(error_text)
print('The bounties could not be loaded: '..error_text)
end):load()The middle of that table is the trap. A query without on_error that fails calls nothing. Whatever was waiting for its result, a player in a menu, a function with a callback, waits forever. Add on_error wherever someone is waiting for the answer.
The error text is the one the database wrote, so it differs from database to database. Show it to an admin or print it; do not make decisions by searching in it.
An error raised by your own code inside a callback is printed as a callback error and does not stop the server. The rest of that callback does not run. Inside a transaction it also rolls the transaction back.
Some plugins keep what they have loaded in memory, because they need it every tick or for every player. The place to load it is the LoadData hook, which Flux runs once per map when the database is ready. Add this to sv_hooks.lua, and Bounties.open = Bounties.open or {} to the top of sv_plugin.lua:
--- Loads the open bounties of the server.
function Bounties:LoadData()
Bounty:where('hunter_id', nil):get(function(bounties)
self.open = bounties
end):on_error(function(error_text)
Flux.abort_data_load('the bounties could not be loaded: '..error_text)
end):load()
endThree things are special here.
Queries wait during LoadData. As in a transaction, a query issued in this hook has been answered when the handler returns, on every database. Nobody is on the server yet, so waiting costs nothing, and the plugins that load after yours can rely on your data.
A failed load must be reported. Flux.abort_data_load(reason) tells Flux that the server does not have its data. Think about what would happen otherwise: the list is empty, the server runs, and whatever later writes "the open bounties" writes an empty list over the real ones. So Flux has a gate. Flux.data_loaded becomes true only when every LoadData handler has finished without an abort. Until then the server lets no player in (they are told that the server is still loading its data) and saves nothing. After an abort it stays that way until the server is restarted, and the console says what could not be loaded.
Check the gate where players can reach you early. Players who stay through a map change are on the server before the data of the new map has loaded. Code that acts on stored data for a player, such as a command or a net message handler, starts with:
if !Flux.check_data_loaded(actor) then return endIt returns whether the data has loaded and tells the player to try again in a moment when it has not.
From here on Bounties.open is a copy, and keeping it right is the job of the plugin: whatever posts a bounty adds it to the list and whatever claims one takes it out. The database does not do that for you. A plugin that collects changes in memory and writes them later does so in the SaveData hook, the counterpart of LoadData. The Bounties plugin writes every change at once and needs none.
So that you do not look for these:
-
Relations are never loaded behind your back. Reading a relation that was not preloaded gives
nil. There is no query hidden in a field access. -
There is no method for summing or joining tables.
countcounts rows; to add up a column, load the rows and add them in Lua, or keep the total in a column. A condition with OR is written as one SQL condition:where('reward >= ? OR reason = ?', 500, 'Graffiti'). -
A record is not refreshed. It holds what the row held when it was loaded plus what you changed, and it does not notice that
update_all, another record or another server has written to the row since.savealso ignores fields that are not columns. -
A relation is found by
<model>_idand nothing else. A second reference to the same table, likehunter_id, is a plain column. -
destroydeletes one row. Dependent rows are the business of the foreign keys. -
A rollback restores the database, not your Lua values, apart from the
idand the loaded state of the records the transaction saved or destroyed. -
Validations are not enforced by the database and are skipped by
upsert,insert,update_allanddelete_all.
| SQLite | PostgreSQL | MySQL and MariaDB | |
|---|---|---|---|
| A callback runs | before the call returns | later | later |
| A misspelled column in a condition | no error, no rows | an error | an error |
Rows handed to the function of upsert
|
none on the SQLite built into the game | the id of each row | the id of each row on MariaDB |
unique_by of upsert
|
names the index that counts | names the index that counts | any unique index that collides counts |
created_at as you read it |
2026-12-02T22:05:36Z |
2026-12-02 22:05:36 |
2026-12-02 22:05:36 |
| Connections | one | up to pool
|
up to pool
|
| Time held by a transaction is printed in development | no | yes | yes |
| Error texts | its own | its own | its own |
The date and time texts differ, so never compare or cut them yourself. time_from_timestamp(text) reads both forms and gives a Unix time, and to_datetime(unix_time) writes the form the current database wants, which is what you pass to where.
- Using a result after the call instead of inside the callback. It works on SQLite and fails on a database server. See Results arrive in a callback.
-
Forgetting
load(). A chain that ends inexpectorgetdoes nothing until it is sent. No error tells you. -
Reading
record.idright aftersave(). It is there in the callback ofsave. -
Reading a relation that was not preloaded. It is
nil, andipairs(nil)is an error. See Relations and preload. - Preloading rows onto a long-lived record that other code changes. The child keeps its old values, and whoever reads it gets them. See A loaded relation is saved with its parent.
-
Putting
nilinto a condition map. The condition disappears and the query matches more; only a map left with no condition at all raises an error. UseActiveRecord.nullfor "is empty" and check ids first. See NULL and ActiveRecord.null. -
Writing the direction of
orderin capitals.order('reward', 'DESC')does not sort at all. Write'desc'. -
Sorting after
all().all()already orders by id, soBounty:all():order('reward', 'desc')is still ordered by id. Start withBounty:order('reward', 'desc'). - Editing a migration that has run. The table does not change. Write a new migration. See Change a table later.
-
Leaving out
on_errorwhere someone waits for the answer. A failed query then calls nothing. See When a query fails. - Trusting a misspelled name to fail. A field that is not a column is not saved, and on SQLite a condition on a column that does not exist matches nothing. Neither is reported.
-
Attaching
after_rollbackat the end of a transaction function, or forgetting to put the Lua values back in it. See Transactions. -
Calling
delete_allorupdate_allwithout awhere. Every row is hit. -
Loading at startup without
Flux.abort_data_load. A failed load then looks like "there is nothing", and nothing is what gets saved. See Loading when the server starts.
| Task | Code |
|---|---|
| Create a table |
create_table('bounties', function(t) ... end) in the change function of a migration |
| Add a column |
add_column('bounties', 'expires_at', 'datetime') in a new migration |
| Add a unique index | add_index('bounty_pledges', { 'bounty_id', 'character_id' }, { unique = true }) |
| Add a check constraint |
add_check_constraint('bounties', 'reward >= 0', { name = 'bounties_reward_not_negative' }), or t:check_constraint('reward >= 0') in create_table
|
| Run the migrations | restart the server, or fpkg db:migrate in the schema folder |
| See what has run |
fpkg db:migrate:status, or flux db:migrate:status in the server console |
| Revert the newest migration |
fpkg db:rollback; fpkg db:migrate:redo to run it again as well |
| Define a model |
class 'Bounty' extends 'ActiveRecord::Base' in models/bounty.lua
|
| Make a record | local bounty = Bounty.new() |
| Insert or update it | bounty:save(function(success, error_text) ... end) |
| Delete it | bounty:destroy(function(success, error_text) ... end) |
| Find by id | Bounty:find(id):expect(function(bounty) ... end):load() |
| Find one by a column | Bounty:find_by('reason', text):expect(function(bounty) ... end):load() |
| The same with the finder of the column |
Bounty:find_by_reason(text, function(bounty) ... end):load(); there once the server has read the table |
| Find many | Bounty:where('character_id', id):get(function(bounties) ... end):load() |
| Count rows |
Bounty:where(...):count(function(amount) ... end, on_error), without load()
|
| Find one or get a new record |
Bounty:where(...):expect(function(bounty) ... end):rescue(function(new_bounty) ... end); rescue sends the query itself |
| Condition with SQL | where('reward >= ?', 100) |
| Condition on several columns | where({ character_id = id, hunter_id = ActiveRecord.null }) |
| One of several values | where({ character_id = { 1, 2 } }) |
| Column is empty, is not empty |
where('hunter_id', nil), where_not('hunter_id', nil)
|
| Sort, limit, skip |
order('reward', 'desc'), limit(10), skip(10)
|
| Catch a failed query |
:on_error(function(error_text) ... end) before :load()
|
| Declare relations |
Bounty:belongs_to 'Character', Bounty:has_many 'bounty_pledges'
|
| Load relations with a query |
:preload('bounty_pledges', 'character'), nested :preload({ bounty_pledges = { 'character' } })
|
| Load relations of a record | bounty:load_relations('bounty_pledges', function() ... end) |
| Validate | Bounty:validates('reason', { presence = true, length = { maximum = 120 } }) |
| Replace the error text of a validation | Bounty:validates('reward', { numericality = { greater_than = 0 }, message = 'Invalid reward' }) |
| Insert or update by a unique index | BountyPledge:upsert(values, { unique_by = { 'bounty_id', 'character_id' } }, on_done, on_error) |
| Find a record or create it | BountyPledge:find_or_create_by(values, function(pledge) ... end, on_error) |
| Change many rows | Bounty:where(...):update_all({ hunter_id = 3 }, function(count) ... end, on_error) |
| Delete many rows | Bounty:where(...):delete_all(function(count) ... end, on_error) |
| Write several things or none |
Bounty:transaction(function(transaction) ... end) with transaction:after_commit(...) and transaction:after_rollback(function(error_text) ... end)
|
| Load at server start |
function Bounties:LoadData() with Flux.abort_data_load(reason) in on_error
|
| Refuse a player until the data is there | if !Flux.check_data_loaded(actor) then return end |
| Text of a date column to Unix time and back |
time_from_timestamp(text), to_datetime(unix_time)
|
General documentation
Developer documentation. To learn how to use and set up Flux, please refer to the general documentation.