MantisDocs

Live queries

Subscribe to a select and get its rows again every time they change.

A live query is a select that stays open. It sends the rows once, then sends them again each time a write changes the result, whoever made the write.

A live query is a select that stays open. It sends the rows once, then sends them again each time a write changes the result, whoever made the write: your Laravel app through Eloquent or Mantis::table(), the browser, the agent or a rewind.

It runs in the browser, over a WebSocket, so in a Laravel app the page's script subscribes with the JavaScript SDK and the publishable key, set up as in Access rules. It reaches tables in the Mantis schema, as far as their rules allow. For a page with no JavaScript of your own, Livewire can poll instead.

On a page

app/todos.tsx
"use client";

import { useQuery } from "@shipmantis/sdk/react";
import { mantis } from "@/lib/mantis";

export function Todos() {
  const { rows, error, loading } = useQuery(mantis, "todos", {
    where: { done: false },
    orderBy: [{ column: "createdAt", direction: "desc" }],
  });

  if (loading) return <p>Loading…</p>;
  if (error) return <p>{error.message}</p>;
  return (
    <ul>
      {rows!.map((todo) => (
        <li key={todo.id}>{todo.title}</li>
      ))}
    </ul>
  );
}

useQuery(client, table, options) takes the same options as select and returns:

FieldWhat it holds
rowsThe latest rows, typed from the schema. undefined until the first answer.
errorA MantisError if the query was refused.
loadingtrue until the first rows or the first error.

Change the options and the hook stops the old query and starts the new one. It stops when the component unmounts.

A browser holds the publishable key, not the secret one. Live queries made with it see only what your access rules allow, so set the rules and a userToken first.

resources/views/todos.blade.php
<ul id="todos"></ul>
@vite('resources/js/todos.js')
resources/js/todos.js
import { mantis } from "./mantis";

const list = document.getElementById("todos");

const stop = mantis.from("todos").live(
  { where: { done: false }, orderBy: [{ column: "createdAt", direction: "desc" }] },
  {
    rows: (todos) => {
      list.replaceChildren(...todos.map((todo) => Object.assign(document.createElement("li"), { textContent: todo.title })));
    },
    error: (error) => console.error(error.status, error.reasons),
  },
);

window.addEventListener("pagehide", stop);

live(options, handlers) takes the same options as select and calls rows with the whole result each time, not the change, so the page can render it as it is. It returns a function that stops the query; after an error the query is stopped. With Alpine, Vue or React on the page, render rows into their state instead.

Another way in

const stop = mantis.from("todos").live(
  { where: { done: false } },
  {
    rows: (rows) => render(rows),
    error: (error) => console.error(error.status, error.reasons),
  },
);

// later
stop();

live(options, handlers) calls rows with the whole result each time, not the change, so you can render it as it is. It returns a function that stops the query. After an error the query is stopped.

Without any JavaScript of your own, a Livewire component can read the rows on the server and poll:

app/Livewire/OpenTodos.php
class OpenTodos extends Component
{
    public function render()
    {
        return view('livewire.open-todos', ['todos' => Todo::where('done', false)->latest('createdAt')->get()]);
    }
}
resources/views/livewire/open-todos.blade.php
<ul wire:poll.2s>
    @foreach ($todos as $todo)
        <li wire:key="{{ $todo->id }}">{{ $todo->title }}</li>
    @endforeach
</ul>

Polling asks every two seconds whether or not anything changed, and works on any table, your migrations' too; a live query is told only when its result changes. Poll for a handful of viewers, subscribe for many.

How it connects

The client opens one WebSocket to /v1/live on the first live query and shares it between all of them. It closes the socket when the last one stops. With a userToken, a query refused because the user's token expired asks for a new token and joins again.

What counts as a change

Every write that changes the result, wherever it came from: the data api, the dashboard, a rewind, your own Postgres connection, a script run with psql. Mantis reads the database's write-ahead log, so nothing is missed by going around the SDK.

  • Writes through the data api reach live queries at once.
  • Writes over your own Postgres connection reach them within about a second.
  • A write that doesn't change the result, like an update to a row outside the where, or one that sets the same values, sends nothing.

Identical queries, the same table, options and user, share one subscription on the server, so a thousand people on the same page cost one query per change, not a thousand.

Examples

A chat room, newest 50 messages:

const { rows } = useQuery(mantis, "messages", {
  where: { roomId },
  orderBy: [{ column: "createdAt", direction: "desc" }],
  limit: 50,
});

Index what the query filters and sorts by, .index("roomId", "createdAt"); every change re-runs it.

The signed-in user's own rows. With a rule.owner("userId") read rule and a userToken, the same query returns each user only their rows:

const { rows: todos } = useQuery(mantis, "todos", { where: { done: false } });

A status that a server job moves along, like the transcoding worker:

const { rows } = useQuery(mantis, "clips", { where: { id: clipId } });
const status = rows?.[0]?.status; // uploaded → transcoding → ready

Outside a browser, in a Node service that reacts to new orders:

const stop = mantis.from("orders").live(
  { where: { status: "paid" }, orderBy: [{ column: "createdAt", direction: "desc" }], limit: 100 },
  { rows: (orders) => syncToWarehouse(orders), error: (error) => log(error) },
);

A chat room, newest 50 messages:

mantis.from("messages").live(
  { where: { roomId }, orderBy: [{ column: "createdAt", direction: "desc" }], limit: 50 },
  { rows: renderMessages },
);

Index what the query filters and sorts by, 'indexes' => [['roomId', 'createdAt']] in database/mantis.php; every change re-runs it. Your controller can post messages with Mantis::table('messages')->insert(...), and every open page shows them.

A status a queued job moves along, like the transcoding job:

<span wire:poll.3s>{{ $clip->fresh()->status }}</span>

or, for a Mantis table, live from the browser:

mantis.from("clips").live({ where: { id: clipId } }, { rows: ([clip]) => (status.textContent = clip?.status ?? "") });

Many viewers of the same page. Identical live queries share one subscription on the server, so a thousand open tabs cost one query per change; a thousand pollers cost a thousand queries every few seconds.

Edge cases

CaseWhat happens
The network dropsThe socket reconnects on its own, every live query joins again and gets the latest rows.
The user's token expiresWith a userToken, the client asks for a new token and joins again. Without one the query gets a 401 error and stops.
A schema push changes the tableRunning queries are planned again on the new schema and keep going. A query on a dropped table or column gets an error and stops.
A rule change takes rows awayThe next result leaves them out.
A big resultEvery change sends the whole result again, so keep limit to what is on screen.
A refused queryerror is called once with a MantisError and the query is stopped; start a new one after fixing the cause.
Many tabsEach tab opens its own socket, with every live query in that tab sharing it.

On this page