Data
Models
model: a schema that is also the calls that read and write it. A model is
declared once; the declaration gives a type, a table, and typed operations
(find, add, set, del, …), kept in this browser (local model) or on
the back end (model), where rules say who may do what. Back to the
map.
Examplea whole program
local model Note title: string body: string = "" done: bool = false changed: time = now always index changed check title.trim() != "" else "a note needs a title"state draft = ""resource notes: Note[] = Note.find({done: false}, {order: "changed desc"}) else []action add Note.add({title: draft})? draft = ""action finish(id: string) Note.set(id, {done: true})?column gap=8 padding=16 row gap=8 input value=draft placeholder="A note" submit=add button "Add" press=add text (failure(add) ?? "") color=danger for n in notes key=n.id row gap=8 text n.title flex=1 button "Done" press=finish(n.id)Mental model#
Declaring a model#
The operations#
Examplea whole program
local model Author name: string uniquelocal model Book title: string author: Author cascade year: int = 2000 index yearstate said: string[] = []task show let ada = Author.one({name: "Ada"})? ?? Author.add({name: "Ada"})? if Book.count({author: ada.id})? == 0 Book.addAll([{title: "Notes", author: ada.id, year: 1843}, {title: "Letters", author: ada.id}])? let old = Book.find({year: before(1900)}, {order: "year", with: ["author"]})? said = old.map(b => `${b.title} by ${b.author?.name ?? "?"}`) let first = Book.find({}, {order: "title", limit: 1})? let next = Book.find({}, {order: "title", limit: 1, after: first.at(-1)})? said.push(`then ${next.map(b => b.title).join(", ")}`)for line in said text lineput and inc#
Examplea whole program
model Tally slug: string key day: string hits: int = 0 ms: number = 0 read anyonemodel Vote poll: string who: id = me choice: string unique poll, who read anyone add if me != none change choice if who == meserver fn hit(slug: string, day: string, ms: number): Tally requires anyone return Tally.put({slug, day, hits: 1, ms}, {hits: inc(1), ms: inc(ms)})?server fn tidy(day: string): number requires signedIn return Tally.setAll({day}, {hits: inc(-1)})?action vote(choice: string) Vote.put({poll: "lunch", choice}) else nonecolumn gap=8 padding=16 button "Soup" press=vote("soup") button "Salad" press=vote("salad")Rows taken together#
Examplea whole program
model Sale day: string shop: string total: number items: int = 1 read anyoneshape ShopDay shop: string total: number items: numberserver fn byShop(day: string): ShopDay[] requires signedIn return Sale.sum({day}, ["total", "items"], {by: ["shop"], order: "total desc", limit: 20})?server fn kinds(): number requires signedIn let counts = Sale.count({}, {by: ["shop", "day"]})? let biggest = Sale.max({}, "total")? return counts.length + (biggest ?? 0)action look let rows = byShop("2026-11-20") else [] log(rows)button "Look" press=lookatomic#
Local models#
Models on the back end#
Examplea whole program
model Member id: id = me name: string read anyone add if me != none change if id == memodel Room name: string unique owner: Member = me read anyone add if me != none change, remove if owner == memodel Message room: Room cascade from: Member = me text: string at: time = now index room, at check text.trim() != "" && text.length <= 4000 else "say something (4000 letters at most)" read anyone add if exists(Member, {id: me}) change if from == me then from == me remove if from == mestate email = ""state password = ""state room = ""state text = ""live rooms: Room[] = Room.find({}, {order: "name"}) else []live messages = Message.find({room: room}, {order: "at", last: 50, with: ["from"]}) else []action join auth.signUp(email, password)? Member.add({name: email.split("@")[0]})?action open(name: string) let r = Room.one({name})? ?? Room.add({name})? room = r.idaction send Message.add({room: room, text: text})? text = ""column gap=8 padding=16 row gap=8 input value=email type=email placeholder="Email" input value=password type=password placeholder="Password" button "Join" press=join row gap=8 for r in rooms key=r.id button r.name press={room = r.id} button "Open the den" press=open("den") for m in messages key=m.id text `${m.from?.name ?? "someone"}: ${m.text}` input value=text submit=send placeholder="Say something" text (failure(send) ?? failure(join) ?? failure(open) ?? "") color=dangerWhat a write sends a page#
A write shows at once#
Examplea whole program
model Message room: string text: string at: time = now check text.trim() != "" else "say something" read anyone add anyone change anyone remove anyonestate draft = ""live messages: Message[] = Message.find({room: "den"}, {order: "at", last: 50}) else []action send Message.add({room: "den", text: draft})? draft = ""action reword(m: Message) Message.set(m.id, {text: `${m.text}!`}) else err => toast("Not changed", err, "error")watch failure(send) let why = failure(send) if why toast("Not sent", why, "error")column gap=8 padding=16 for m in messages key=m.id row gap=8 opacity=(pending(m) ? 0.5 : 1) text m.text button "!" press=reword(m) button "Remove" press={Message.del(m.id)?} input value=draft submit=send placeholder="Say something"Examplea whole program
model Order what: string at: time = now confirmed read anyone add anyonemodel Note text: string read anyone add anyonestate what = ""live orders: Order[] = Order.find({}, {order: "at"}) else []action place Order.add({what})? confirmed Note.add({text: `ordered ${what}`})? what = ""column gap=8 padding=16 input value=what submit=place button "Order" press=place disabled=pending(place) for o in orders key=o.id text o.whatA long list, a window at a time#
Examplea whole program
model Order number: int key customer: string placed: time = now index placed read anyone add anyonelive orders = Order.find({}, {order: "placed desc", window: 200}) else []column gap=8 padding=16 text `${orders.length} orders` column height=480 overflow-y=auto for o in orders key=o?.number virtual=36 if o row height=36 gap=12 align-items=center text `#${o.number}` width=80 text o.customer else row height=36 align-items=center color=dim text "…"Rules#
Examplea whole program
model Member id: id = me name: string read anyone add if me != nonemodel Message from: Member = me text: string edited: bool = false pinned: bool = false reacts: {emoji: string, who: string[]}[] = [] replies: int = 0 read anyone add if me != none change text if from == me change pinned, reacts if me != none remove if from == me// What the page cannot be trusted to say is said here.server before Message.change(was, now) if now.text != was.text now.edited = trueserver before Message.remove(was) if was.pinned fail("unpin it first")?// A field no rule names is the back end's alone.server fn replied(to: string): number requires signedIn let m = Message.get(to)? return Message.set(to, {replies: (m?.replies ?? 0) + 1})?.repliesstate text = ""live messages = Message.find({}, {order: "text"}) else []action reword(id: string) Message.set(id, {text})?action pin(id: string, on: bool) Message.set(id, {pinned: on})?column gap=8 padding=16 input value=text placeholder="New words" for m in messages key=m.id row gap=8 text `${m.text}${m.edited ? " (edited)" : ""}` flex=1 button "Reword" press=reword(m.id) button (m.pinned ? "Unpin" : "Pin") press=pin(m.id, !m.pinned) text (failure(reword) ?? failure(pin) ?? "") color=dangerFiles#
Examplea whole program
model Member id: id = me name: string read anyone add if me != nonemodel Channel name: string private: bool = false owner: Member = me read if !private || owner == me || exists(Seat, {channel: id, who: me}) add if me != nonemodel Seat channel: Channel cascade who: Member read anyone add, remove if exists(Channel, {id: channel, owner: me})// One row a file: a message may have several.model Attachment channel: Channel cascade from: Member = me file: file at: time = now read if exists(Channel, {id: channel, private: false}) || exists(Seat, {channel: channel, who: me}) add if exists(Channel, {id: channel, private: false}) || exists(Seat, {channel: channel, who: me}) remove if from == mestate channel = ""live attached = Attachment.find({channel: channel}, {order: "at"}) else []action attach let picked = fs.pick("image/*,video/*,application/pdf")? if picked let kept = files.upload(picked)? Attachment.add({channel: channel, file: kept})?action dropped(f: {name: string, path: string, data: bytes}) Attachment.add({channel: channel, file: files.upload(f)?})?column gap=8 padding=16 drop=dropped button "Attach" press=attach disabled=pending(attach) if pending(attach) || pending(dropped) progress value=files.progress max=1 for a in attached key=a.id row gap=8 if a.file.type.startsWith("image/") image a.file.url width=96 else if a.file.type.startsWith("video/") video src=a.file.url controls=true width=240 a a.file.name href=`${a.file.url}?download` text `${Math.round(a.file.size / 1024)} KB` color=dim text (failure(attach) ?? failure(dropped) ?? "") color=dangerSeveral uploads at once#
Examplea whole program
model Attachment file: file read, add if me != noneshape Tray name: string up: sendingstate tray: Tray[] = []action send(f: {name: string, path: string, data: bytes}) let up = files.sending() tray = [...tray, {name: f.name, up}] Attachment.add({file: files.upload(f, {into: up})?})?column gap=8 padding=16 drop=send text "Drop files here" for t in tray row gap=8 align-items=center text t.name progress value=t.up.sent max=1 if t.up.state == "sending" button "Cancel" press={t.up.cancel()} else text t.up.state color=dimA download's name#
A picture kept beside a file#
Examplea whole program
// A photo with a small version of itself, and a name of the person's own to save it under.model Member id: id = me name: string read anyone add if me != nonemodel Photo owner: Member = me name: string file: file read if owner == me add if me != none change name if owner == me// A small one is made from the photo and kept beside it.server fn small(id: string): string requires signedIn let me = auth.me()? let p = Photo.get(id)? if p == none || p.owner != me?.id return "" let made = img.resize(img.decode(files.bytes(p.file)?)?, 240, 0)? files.derive(p.file, "thumb", img.png(made)?)? return `${p.file.url}/thumb`live photos = Photo.find({}) else []action add let picked = fs.pick("image/*")? if picked != none let p = Photo.add({name: picked.name, file: files.upload(picked)?})? small(p.id)?column gap=8 padding=16 button "Add a photo" press=add for p in photos row gap=8 image `${p.file.url}/thumb` width=120 a p.name href=`${p.file.url}?download=${p.name.replaceAll("%", "%25").replaceAll("#", "%23")}`In a server fn, and hooks#
Examplea whole program
model Card title: string column: string = "todo" owner: id = me read, add if me != none change if owner == memodel Trail what: string at: time = now// Run around a model's writes, whoever makes them.server before Card.add(c) c.title = c.title.trim() if c.title == "" fail("a card needs a title")?server after Card.change(was, now) Trail.add({what: `${was.title}: ${was.column} to ${now.column}`})?// The back end's own code is not checked by the rules…server fn move(a: string, b: string, to: string): number requires signedIn atomic Card.set(a, {column: to})? Card.set(b, {column: to})? return Card.count({column: to})?// …unless it says so: with the rules of whoever is calling.server fn mine(): Card[] requires signedIn return Card.as(me).find({column: "todo"})?state said = ""action go let c = Card.add({title: " Sand the top "})? said = `${c.title}: ${move(c.id, c.id, "doing")?} doing, ${mine()?.length} of mine to do`button "Go" press=gotext saidWho is writing#
Examplea whole program
model Member id: id = me name: string read anyone add if me != nonemodel Upload owner: Member = me name: string at: time = now read anyone add if me != none// The page's uploads are dated now, whatever the page says. The back end's// own code may date one as it likes: a file brought in from somewhere else.server before Upload.add(u) if caller.page u.at = Date.now()server fn bringIn(name: string, at: number): Upload requires signedIn return Upload.add({name, at})?live uploads = Upload.find({}, {order: "at desc"}) else []action old bringIn("minutes.pdf", 0)?column gap=8 padding=16 button "Bring one in" press=old for u in uploads key=u.id text u.nameA private field#
Examplea whole program
model Member id: id = me name: string read anyone add if me != nonemodel Vote poll: string choice: number who: Member = me private unique poll, who read anyone add if me != none change choice if who == me remove if who == mestate poll = "lunch"live votes: Vote[] = Vote.find({poll}) else []action choose(n: number) let mine = votes.find(v => v.who != none) if mine Vote.set(mine.id, {choice: n})? else Vote.add({poll, choice: n})?row gap=8 padding=16 for n in [1, 2, 3] button `${n}: ${votes.filter(v => v.choice == n).length}` press=choose(n)What a server fn returns#
Examplea whole program
model Account id: id = me name: string token: string = "" hidden read anyone add if me != noneshape Board mine: Account? all: Account[]// The fn compares tokens; the page is sent rows with no `token` in them.server fn board(token: string): Board requires anyone let all = Account.find({}, {order: "name"})? return {mine: all.find(a => a.token == token), all}resource b: Board = board("") else {mine: none, all: []}for a in b.all text a.nameA queue the page never sees#
Examplea whole program
model Member id: id = me name: string read anyone add if me != nonemodel Message from: Member = me text: string read anyone add if me != none// No rule: only the back end's own code reaches it.model Job kind: string payload: json state: string = "waiting" tries: int = 0 due: time = now index state, due// The message and the job it causes are kept together, or neither is.server fn say(text: string): Message requires signedIn atomic let m = Message.as(me).add({text})? Job.add({kind: "mail", payload: {message: m.id}})? return m// What was being done when the back end stopped is done again.server start Job.setAll({state: "running"}, {state: "waiting"})?// The job due first, if one is due: taken, done, and marked. One that fails is// tried again later, five times.server every 1000 let job = Job.take({state: "waiting", due: before(Date.now())}, {state: "running"}, {order: "due"})? if job let answer = net.text(`https://mail.example/send?job=${job.id}`) else "" if answer == "sent" Job.set(job.id, {state: "done"})? else if job.tries < 5 Job.set(job.id, {state: "waiting", tries: job.tries + 1, due: Date.now() + 60000 * (job.tries + 1)})? else Job.set(job.id, {state: "failed"})?state text = ""live messages = Message.find({}) else []action send say(text)? text = ""column gap=8 padding=16 for m in messages key=m.id text m.text input value=text submit=send placeholder="Say something" text (failure(send) ?? "") color=dangerModels chosen at run time#
Examplea whole program
model Order title: string total: number = 0 note: string = "" hidden by: id = me read if by == me add if me != none change title if by == merule staff = exists(Order, {by: me, title: "staff"})// What there is to browse.server fn tables(): string[] requires staff let all = models.list()? return all.map(m => `${m.name}: ${m.fields.map(f => `${f.name} ${f.type}`).join(", ")}`)// A page of any model's rows, as the caller's own page would be given them.server fn browse(model: string, after: json): json[] requires staff return models.of(model).as(me).find({}, {limit: 50, after})?// The same, as the back end has them: past the rules, hidden fields and all.server fn audit(model: string): number requires staff return models.of(model).count({})?state said = ""action look said = `${tables()?.join("; ")} · ${browse("Order", none)?.length} · ${audit("Order")?}`button "Look" press=looktext saidFull-text search#
Examplea whole program
model Member id: id = me name: string read anyone add if me != nonemodel Channel name: string private: bool = false owner: Member = me read if !private || owner == me || exists(Seat, {channel: id, who: me}) add if me != nonemodel Seat channel: Channel cascade who: Member unique channel, who read if who == me add if exists(Channel, {id: channel, owner: me})model Message channel: Channel cascade from: Member = me text: string at: time = now index channel, at index text fulltext read if exists(Channel, {id: channel, private: false}) || exists(Seat, {channel: channel, who: me}) add if exists(Channel, {id: channel, private: false}) || exists(Seat, {channel: channel, who: me})state words = ""state newest = false// (Put around each hit in a snippet: something no message holds.)fn lit(): string = "\u0001"live found = Message.searchCount(words) else 0live hits = Message.search(words, {}, {order: newest ? "at desc" : "rank", limit: 20, snippet: {mark: lit(), around: 16}}) else []column gap=8 padding=16 row gap=8 input value=words placeholder="Search messages" flex=1 button (newest ? "Newest first" : "Best first") press={newest = !newest} text `${found} found` color=dim for h in hits key=h.id text for piece, i in h.snippet.split(lit()) key=i if i % 2 == 1 mark piece else text pieceChanging a schema#
A change to the data itself: migrate#
Examplea whole program
model Entry what: string // As it was typed, in the first build; and what it comes to, in this one. amount: string cents: int = 0 read anyone add if true// Run once for a database, when the back end starts on it: the rows that// were there are given their cents.migrate "amounts as cents" for e in Entry.find({cents: 0})? Entry.set(e.id, {cents: Math.round(Number(e.amount) * 100)})?// Raw SQL, for what is quicker said so.migrate "what, tidied" sql.run(sql.open("app")?, "update Entry set what = trim(what)")?live entries = Entry.find({}, {order: "what"}) else []for e in entries key=e.id text `${e.what}: ${e.cents / 100}`For agents#
Refused#
Pitfalls#
In the source#
Edit this page:
docs/models.md