Skip to main content
Version: 1.2.1

ORM

The main module. This is the entry point of the library.


ORM.model(tableName, fields, opts?)

Creates a new model linked to a MySQL table.

Parameters

ParameterTypeRequiredDescription
tableNamestringYesName of the MySQL table
fieldstableYesSchema: { column = "type", ... }
optstableNoOptions (see below)

Options (opts)

OptionTypeDefaultDescription
primaryKeystring"id"Name of the primary key column

Available field types

TypeDescription
"string"Text
"number"Number
"boolean"True/false
"json"Lua table automatically converted to JSON
"auto"Automatic detection (table → JSON, JSON string → table)

Return

OrvexModel — A model object with all CRUD methods, the query builder, and relations.

Example

local User = OrvexORM.model("users", {
identifier = "string",
money = "number",
job = "string",
position = "json",
metadata = "auto",
}, { primaryKey = "identifier" })

ORM.transaction(adapter?)

Creates a new transaction builder to execute multiple queries atomically.

Parameters

ParameterTypeRequiredDescription
adapterOrvexAdapterNoCustom adapter (uses the default otherwise)

Return

OrvexTransaction — A transaction object with the methods insert, update, delete, upsert, addRaw, commit.

Example

local tx = OrvexORM.transaction()
tx:insert("users", { identifier = "license:abc", money = 500 })
tx:update("vehicles", { owner = "license:abc" }, { plate = "ABC123" })
local success = tx:commit()

ORM.enableCache(opts?)

Enables the global cache with an optional TTL.

Parameters

OptionTypeDefaultDescription
ttlnumber60Time to live in seconds

Example

OrvexORM.enableCache({ ttl = 30 })

ORM.disableCache()

Disables and clears the global cache.

OrvexORM.disableCache()

ORM.flushCache()

Clears all cache entries without disabling it.

OrvexORM.flushCache()

ORM.cacheStats()

Returns global cache statistics.

Return

table{ hits, misses, hitRate, entries }

FieldTypeDescription
hitsnumberNumber of cache hits
missesnumberNumber of cache misses
hitRatenumberHit ratio (hits / (hits + misses))
entriesnumberNumber of entries currently in the cache

Example

local stats = OrvexORM.cacheStats()
print(("Cache: %d hits, %d misses (%.0f%% hit rate), %d entries")
:format(stats.hits, stats.misses, stats.hitRate * 100, stats.entries))

ORM.setAdapter(adapter)

Replaces the default database adapter.

OrvexORM.setAdapter(Adapter.new(MyDriver.new()))

ORM.migrations(migrations)

Registers a list of migrations to apply.

Parameters

ParameterTypeRequiredDescription
migrationstable[]YesList of migrations with name, up, down

Example

OrvexORM.migrations({
{
name = "001_create_users",
up = function(schema)
schema:create("users", function(t)
t:primaryString("identifier", 60)
t:integer("money")
t:string("job")
end)
end,
down = function(schema)
schema:drop("users")
end,
},
})

ORM.migrate(adapter?)

Runs all pending migrations.

Parameters

ParameterTypeRequiredDescription
adapterOrvexAdapterNoCustom adapter (uses the default otherwise)

Return

number — The number of applied migrations.

Example

local count = OrvexORM.migrate()
print(count .. " migration(s) applied")

ORM.rollback(adapter?)

Rolls back the last batch of migrations.

Parameters

ParameterTypeRequiredDescription
adapterOrvexAdapterNoCustom adapter (uses the default otherwise)

Return

number — The number of rolled back migrations.

Example

local count = OrvexORM.rollback()
print(count .. " migration(s) rolled back")

ORM.raw(sql, params?)

Executes a raw SQL query (SELECT) and returns the rows.

local rows = OrvexORM.raw("SELECT * FROM users WHERE money > ?", { 1000 })

ORM.rawExec(sql, params?)

Executes a raw SQL query (INSERT/UPDATE/DELETE).

OrvexORM.rawExec("UPDATE users SET money = money + ? WHERE job = ?", { 100, "police" })

ORM.debug(enabled)

Enables or disables debug mode. When enabled, all SQL queries are printed to the console.

OrvexORM.debug(true) -- Enable SQL logs
OrvexORM.debug(false) -- Disable logs

ORM.seed(fn)

Runs a seed function to populate the database with initial data.

OrvexORM.seed(function(orm)
local User = orm.model("users", { identifier = "string", money = "number" })
User.create({ identifier = "license:admin", money = 99999 })
User.create({ identifier = "license:test", money = 500 })
end)

ORM.introspect(tableName, adapter?)

Analyzes an existing MySQL table and returns its field definition and primary key. Uses DESCRIBE internally.

Parameters

ParameterTypeRequiredDescription
tableNamestringYesName of the MySQL table to analyze
adapterOrvexAdapterNoCustom adapter

Return

table<string, OrvexFieldType>, string — The detected fields and the primary key name.

MySQL type mapping

MySQL TypeOrvexORM Type
int, bigint, float, double, decimal"number"
varchar, char, text, enum"string"
tinyint(1)"boolean"
json"json"
datetime, timestamp, date"string"

Example

local fields, pk = OrvexORM.introspect("users")
-- fields = { id = "number", name = "string", money = "number", ... }
-- pk = "id"

-- Create a model automatically
local User = OrvexORM.model("users", fields, { primaryKey = pk })

ORM.fromTable(tableName, opts?)

Shortcut that combines introspect() and model(): analyzes the table and creates the model automatically.

local User = OrvexORM.fromTable("users")
-- Equivalent to:
-- local fields, pk = OrvexORM.introspect("users")
-- local User = OrvexORM.model("users", fields, { primaryKey = pk })