Skip to content

NormOrm class

The ORM instance returned by Norm.new. Defines models, runs migrations, and owns the adapter.

Auto-generated

This page is generated from the source annotations by scripts/gen-api.mjs. Edit the LuaCATS doc comments in the Norm sources, not here.

🔗 Source: src/orm.lua

MemberReturnsDescription
adapter
defineNormModelDefine and register a model from a schema (a { column = Norm.types.* } map).
executeNormExecResultPromise (async)Run a raw parameterised write (INSERT/UPDATE/DELETE/DDL).
foreign_keysWhether sync() emits SQL FOREIGN KEY constraints.
is_readybooleanWhether operations run immediately.
jsonProvider used to (de)serialise json columns.
log
migrateNormPromise (async)Run pending schema migrations in order, recording applied ones in a
modelNormModel|nilGet a previously defined model.
models
providerA promise provider plugs a framework's promise type into Norm.
queryNormRowsPromise (async)Run a raw parameterised SELECT (bypassing the query builder).
supports_transactionsbooleanWhether the configured adapter supports transactions.
syncNormBooleanPromise (async)Create the table of every registered model (CREATE TABLE IF NOT EXISTS),
transactionNormPromise (async)Run fn inside a database transaction: BEGIN, then every operation fn

adapter field

lua
NormAdapter

define method

lua
NormOrm:define(table_name: string, schema: table<string, NormColumn>, options?: NormDefineOptions)
  -> NormModel

Define and register a model from a schema (a { column = Norm.types.* } map). The returned model is your handle for all CRUD/query operations.

lua
    local User = db:define("users", {
        id    = Norm.types.id(),
        name  = Norm.types.string({ length = 64, nullable = false }),
        email = Norm.types.string({ length = 128, unique = true }),
        coins = Norm.types.integer({ default = 0 }),
    })

execute async method

lua
NormOrm:execute(query: string, params?: any[])
  -> promise: NormExecResultPromise

Run a raw parameterised write (INSERT/UPDATE/DELETE/DDL). Resolves with a { affectedRows, insertId } table.

lua
    local res = db:execute("DELETE FROM `users` WHERE `id` = ?", { 1 }):await()
    print(res.affectedRows)

foreign_keys field

lua
boolean|"auto"

Whether sync() emits SQL FOREIGN KEY constraints.

is_ready method

lua
NormOrm:is_ready()
  -> boolean

Whether operations run immediately. With queue_until_ready, false until the first successful sync()/migrate(); otherwise always true.

json field

lua
NormJsonProvider

Provider used to (de)serialise json columns.

log field

lua
boolean

migrate async method

lua
NormOrm:migrate(migrations: NormMigration[])
  -> promise: NormPromise

Run pending schema migrations in order, recording applied ones in a norm_migrations table so each runs exactly once. Idempotent: re-running applies only what's new. Resolves with the list of ids applied this run.

lua
    db:migrate({
        { id = "2026_06_25_add_last_seen", up = function(m)
            m:add_column("players", "last_seen", Norm.types.datetime())
            m:add_index("players", "idx_players_account", { "account_id" }, { unique = true })
        end },
    }):await()

model method

lua
NormOrm:model(table_name: string)
  -> NormModel|nil

Get a previously defined model.

lua
    local User = db:model("users")

models field

lua
table<string, NormModel>

provider field

lua
NormPromiseProvider

A promise provider plugs a framework's promise type into Norm. Built-in builders: Norm.promise.builtin|nanos|cfx. Validate a custom one with Norm.promise.define.

query async method

lua
NormOrm:query(query: string, params?: any[])
  -> promise: NormRowsPromise

Run a raw parameterised SELECT (bypassing the query builder). Resolves with the raw rows. Bind values with ? placeholders, never interpolate.

lua
    local rows = db:query("SELECT * FROM `users` WHERE `coins` > ?", { 100 }):await()

supports_transactions method

lua
NormOrm:supports_transactions()
  -> boolean

Whether the configured adapter supports transactions.

sync async method

lua
NormOrm:sync()
  -> promise: NormBooleanPromise

Create the table of every registered model (CREATE TABLE IF NOT EXISTS), in dependency order so foreign keys resolve. When foreign keys are enabled (see the foreignKeys option), belongsTo relations emit FOREIGN KEY constraints. Resolves true.

lua
    db:sync():await() -- run once at startup, after defining your models

transaction async method

lua
NormOrm:transaction(fn: fun(orm: NormOrm):<T>)
  -> promise: NormPromise

Run fn inside a database transaction: BEGIN, then every operation fn performs (await them) runs on that transaction; COMMIT if fn returns, ROLLBACK if it raises. Resolves with fn's return value (rejects with its error after rolling back). Use :await() on operations inside fn as usual.

Throws immediately if the adapter does not support transactions — check db:supports_transactions() first if you need to branch (nanos has no transaction API, so it always throws there; oxmysql supports them). Do not overlap transactions on the same Norm instance (the state is per-instance).

lua
    db:transaction(function()
        from.coins = from.coins - 100; from:save():await()
        to.coins   = to.coins + 100;   to:save():await()
    end):await()