Schema versions
Describe your tables as numbered steps. waw-sql applies the missing ones in order and never runs a step twice, so nobody imports .sql files by hand again.
Describing your tables
A server owner no longer imports .sql files by hand, and an update that needs a new column just adds one more step.
MySQL.migrate.await({
{ 1, 'garage table', [[
CREATE TABLE IF NOT EXISTS my_garage (
id INT AUTO_INCREMENT PRIMARY KEY,
plate VARCHAR(8) NOT NULL,
owner VARCHAR(50) NOT NULL
)
]] },
{ 2, 'plate index', 'ALTER TABLE my_garage ADD UNIQUE INDEX plate (plate)' },
-- one step may hold several queries
{ 3, 'state column', {
'ALTER TABLE my_garage ADD COLUMN state TINYINT NOT NULL DEFAULT 1',
'UPDATE my_garage SET state = 0 WHERE owner = ""',
} },
})const steps = [
[1, 'garage table', 'CREATE TABLE IF NOT EXISTS my_garage (id INT AUTO_INCREMENT PRIMARY KEY, plate VARCHAR(8) NOT NULL, owner VARCHAR(50) NOT NULL)'],
[2, 'plate index', 'ALTER TABLE my_garage ADD UNIQUE INDEX plate (plate)'],
];
(async () => {
const result = await exports['waw-sql'].migrate_async(steps);
console.log(`my_garage is at version ${result.version}`);
})();The rules
- Call it once when your script starts, before the first query that needs the tables. In Lua, the simplest place is inside
MySQL.ready(function() ... end), since.awaitneeds a thread. It returns{ applied = { ... }, version = n }: the steps applied by this call and the version the script is at now. - A step is
{ version, name, sql }or{ version = 1, name = '...', sql = ... }. Versions are whole numbers starting at 1; the name is only for people. - If a step fails, the steps after it are not applied.
MySQL.migrate.awaitraises the error;MySQL.migrate(steps, function(result, err) end)gives it to the callback. Fix the step and start the script again: it continues where it stopped. - A step that only changes data (INSERT, UPDATE, DELETE) is undone as a whole when it fails. MariaDB cannot undo changes to a table's structure (CREATE, ALTER, DROP), so put one such change in a step.
Servers that already applied it will not run it again. Add a new step instead. An edited step is flagged in the panel.
Where it is kept
Which step was applied is kept per resource name in the waw_sql_migrations table, created the first time a script calls MySQL.migrate. The panel shows every script's version and steps under Maintenance → Schema in the advanced view. From code, the migrations export gives the same; see Exports & events.
Running on oxmysql too
MySQL.migrate exists only in waw-sql. A script that must also run on oxmysql can check for it:
if GetResourceState('waw-sql') == 'started' then
MySQL.migrate.await(steps)
else
-- your own CREATE TABLE IF NOT EXISTS
end