Skip to content

Tutorial — Part 2: Database, Migrations & Models

In Part 2, we will create the SQLite schema using transactional SQL migrations (ob db migrate) and build clean Django/Exposed-style models using ob:db.


1. Generate & Run a SQL Migration

Create a new timestamped migration file:

ob g migration create_blog_tables

Edit migrations/<timestamp>_create_blog_tables.sql:

CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    email TEXT NOT NULL UNIQUE,
    password_hash TEXT NOT NULL,
    created_at TEXT DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE IF NOT EXISTS posts (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    author_id INTEGER NOT NULL REFERENCES users(id),
    title TEXT NOT NULL,
    slug TEXT NOT NULL UNIQUE,
    body TEXT NOT NULL,
    published INTEGER NOT NULL DEFAULT 1,
    created_at TEXT DEFAULT CURRENT_TIMESTAMP
);

Apply pending migrations and verify status:

ob db migrate
ob db status

Orbita executes each migration inside a transaction and records it in _orbita_migrations.


2. Define Models (ob:db)

db.default() opens the shared SQLite connection configured in config.toml (or ORBITA_DB). Each app defines its own model.tyl and returns the table object directly.

src/apps/auth/model.tyl

local db = require("ob:db")
local conn = db.default()

local Users = conn:table("users", {
    id = db.integer():primary_key():auto_increment(),
    name = db.text():not_null(),
    email = db.text():not_null():unique(),
    password_hash = db.text():not_null(),
    created_at = db.text():default("CURRENT_TIMESTAMP"),
})

return Users

src/apps/posts/model.tyl

local db = require("ob:db")
local conn = db.default()

local Posts = conn:table("posts", {
    id = db.integer():primary_key():auto_increment(),
    author_id = db.integer():not_null(),
    title = db.text():not_null(),
    slug = db.text():not_null():unique(),
    body = db.text():not_null(),
    published = db.integer():default(1),
    created_at = db.text():default("CURRENT_TIMESTAMP"),
})

return Posts

3. ActiveRecord Shortcuts & JOIN Queries

With Posts and Users, you get both zero-boilerplate CRUD shortcuts and a fluent SQL query builder:

-- ActiveRecord-style shortcuts
local id = Posts:create({
    author_id = 1,
    title = "Hello Orbita",
    slug = "hello-orbita",
    body = "First post powered by Luau + Rust!",
})
local post = Posts:find(id)
Posts:update(id, { title = "Hello Orbita v0.2" })
Posts:destroy(id)

-- Fluent SQL DSL with JOIN
local published_posts = Posts
    :select("posts.id", "posts.title", "posts.body", "posts.created_at", "users.name AS author_name")
    :join("users", "users.id = posts.author_id")
    :where("posts.published = ?", 1)
    :order_by("posts.id DESC")
    :limit(20)
    :all()

Previous: ← Part 1: Project & Routing · Next: Part 3: Views, Templates & Components →