MantisDocs

Queries

Select, insert, update and delete with a client typed from your schema.

The client

lib/mantis.ts
import { createClient } from "@shipmantis/sdk";
import schema from "../mantis/schema";

export const mantis = createClient({
  url: process.env.MANTIS_URL!,
  key: process.env.MANTIS_SECRET_KEY!,
  schema,
});
OptionWhat it does
urlhttps://data.shipmantis.com, written to .env.local by init.
keyThe secret key on a server, the publishable key in a browser.
schemaYour schema. It is only used for types, so tables, columns and rows are checked.
branchThe branch to query. Default: main.
userTokenA function that returns the signed-in user's token, for access rules.

mantis.from(table) gives you the table's client. Every call returns the rows it read or changed, typed from the schema.

use Shipmantis\Mantis\Laravel\Facades\Mantis;

$todos = Mantis::table('todos');
Mantis::onBranch('try-tags')->table('todos'); // another branch

The facade reads MANTIS_URL, MANTIS_SECRET_KEY and MANTIS_BRANCH from .env, and Shipmantis\Mantis\Mantis can be injected instead. Every call returns the rows it read or changed as arrays. PHP holds the secret key, so its queries skip the access rules.

Mantis::table() reaches the tables in the Mantis schema: the ones mantis/schema.ts or Mantis::applySchema() declared. Tables your Laravel migrations made are plain Postgres; query them with Eloquent or the DB facade.

Select

const todos = mantis.from("todos");

const open = await todos.select({
  columns: ["id", "title"],
  where: { done: false, dueAt: { lt: new Date().toISOString() } },
  orderBy: [{ column: "dueAt", direction: "asc" }],
  limit: 20,
  offset: 40,
});
//    ^? { id: string; title: string }[]
$open = Mantis::table('todos')->select(
    where: ['done' => false, 'dueAt' => ['lt' => now()->toIso8601ZuluString()]],
    columns: ['id', 'title'],
    orderBy: [['column' => 'dueAt', 'direction' => 'asc']],
    limit: 20,
    offset: 40,
);

$first = Mantis::table('todos')->first(['done' => false]); // one row or null
  • columns picks the columns to return. Leave it out for all of them.
  • orderBy sorts by one or more columns, asc by default. Rows are always sorted by id last, so pages are stable. Without orderBy, rows come oldest first.
  • limit is 100 by default and at most 1000. offset skips rows.

Where

Every key in where must hold, so the conditions are joined with AND. A plain value means equal; an object compares:

OperatorMeans
eq, neequal, not equal
lt, lte, gt, gteless than, at most, greater than, at least
inequal to one of a list
await todos.select({ where: { listId: { in: [inbox, today] }, title: { ne: "" } } });
Mantis::table('todos')->select(['listId' => ['in' => [$inbox, $today]], 'title' => ['ne' => '']]);

null asks for an empty column: { dueAt: null } and { dueAt: { eq: null } } both mean is null, and { dueAt: { ne: null } } means is not null. A ne with a value keeps the rows where the column is empty.

Insert

const [todo] = await todos.insert({ title: "Ship it", listId: inbox });
await todos.insert([{ title: "One", listId: inbox }, { title: "Two", listId: inbox }]);
[$todo] = Mantis::table('todos')->insert(['title' => 'Ship it', 'listId' => $inbox]);
Mantis::table('todos')->insert([
    ['title' => 'One', 'listId' => $inbox],
    ['title' => 'Two', 'listId' => $inbox],
]);

Pass one row or an array of up to 1000. Columns that are optional or have a default can be left out. The rows come back with id and createdAt filled.

Update and delete

await todos.update({ set: { done: true }, where: { id: todo.id } });
await todos.delete({ where: { done: true } });

Both need a where, so a missing filter can't change every row by accident. To mean every row, say so with where: {}.

Mantis::table('todos')->update(['done' => true], ['id' => $todo['id']]);
Mantis::table('todos')->delete(['done' => true]);

Both take the where as a required argument. To mean every row, pass [].

Errors

A refused call throws a MantisError with the HTTP status and a list of reasons:

import { MantisError } from "@shipmantis/sdk";

try {
  await todos.insert({ title: "No list" } as never);
} catch (error) {
  if (error instanceof MantisError) {
    console.log(error.status, error.reasons);
    // 422 [ ... ]
  }
}

A refused call throws a MantisException with the HTTP status() and the reasons():

use Shipmantis\Mantis\MantisException;

try {
    Mantis::table('todos')->insert(['title' => 'No list']);
} catch (MantisException $error) {
    if ($error->unreachable()) {
        // Mantis could not be reached; status() is 0.
    }
    logger()->warning($error->getMessage(), ['status' => $error->status(), 'reasons' => $error->reasons()]);
}
StatusWhen
401The user token is not valid for the project, or the schema has no auth to check it.
402The team's plan is out of room. Delete rows or move to Pro.
403The access rules refuse the call.
422The query is not valid, or Postgres refused a value or a constraint. Nothing was changed.

Examples

Newest first, page by page. Offsets get slow and shift when rows are added; a cursor on createdAt doesn't:

const page = await mantis.from("posts").select({
  where: before ? { createdAt: { lt: before } } : {},
  orderBy: [{ column: "createdAt", direction: "desc" }],
  limit: 20,
});
const nextBefore = page.at(-1)?.createdAt;

Add an index on what you sort and filter by: .index("createdAt"), or .index("authorId", "createdAt") for one author's posts.

One of several values. Conditions are joined with AND, so ask for alternatives with in:

await mantis.from("orders").select({ where: { status: { in: ["paid", "shipped"] } } });

Rows from two tables. There are no joins; read the ids, then the related rows in one more call:

const posts = await mantis.from("posts").select({ limit: 20 });
const authors = await mantis.from("profiles").select({
  where: { userId: { in: [...new Set(posts.map((post) => post.authorId))] } },
});

Insert or update. Read first, then write the one that applies:

const [existing] = await mantis.from("settings").select({ where: { userId }, limit: 1 });
if (existing) await mantis.from("settings").update({ set: { theme }, where: { id: existing.id } });
else await mantis.from("settings").insert({ userId, theme });

Two requests racing can both insert. Where that matters, do it from one place, your server, for each user.

Newest first, page by page. Offsets get slow and shift when rows are added; a cursor on createdAt doesn't:

$page = Mantis::table('posts')->select(
    where: $before ? ['createdAt' => ['lt' => $before]] : [],
    orderBy: [['column' => 'createdAt', 'direction' => 'desc']],
    limit: 20,
);
$nextBefore = end($page)['createdAt'] ?? null;

Add an index on what you sort and filter by, in the schema: .index("createdAt"), or .index("authorId", "createdAt") for one author's posts. For a table your migrations made, $table->index(['author_id', 'created_at']).

One of several values. Conditions are joined with AND, so ask for alternatives with in:

Mantis::table('orders')->select(['status' => ['in' => ['paid', 'shipped']]]);

Rows from two tables. The data api has no joins; read the ids, then the related rows in one more call. Tables your migrations made can join in SQL as usual, through Eloquent.

$posts = Mantis::table('posts')->select(limit: 20);
$authors = Mantis::table('profiles')->select([
    'userId' => ['in' => array_values(array_unique(array_column($posts, 'authorId')))],
]);

Insert or update. Read first, then write the one that applies:

$existing = Mantis::table('settings')->first(['userId' => $userId]);
$existing
    ? Mantis::table('settings')->update(['theme' => $theme], ['id' => $existing['id']])
    : Mantis::table('settings')->insert(['userId' => $userId, 'theme' => $theme]);

Two requests racing can both insert. Where that matters, run it in a queued job keyed by the user, or use Eloquent's updateOrCreate with a unique index on a table your migrations made.

Edge cases

CaseWhat happens
limit above 1000, or an insert of more than 1000 rows422. Page through, or split the insert.
An insert of many rows where one is invalid422, and none of them is inserted.
update or delete without where422; nothing is changed. Pass where: {} to mean every row.
A where that matches nothingAn empty array, not an error.
A column or table that isn't in the schema422, naming it. Push the schema first.
A required column left out of an insert422. Give it a value, a .default(...) or make it .optional().
A value of the wrong type, like text in a t.integer()422 from Postgres; nothing is changed.
An integer above 2^53t.integer() is a 64-bit bigint, but JavaScript numbers are exact only to 2^53. Keep larger ids in t.text().
TimestampsSent and returned as ISO 8601 strings in UTC; compare them with lt and gt as strings from toISOString() (toIso8601ZuluString() in PHP).
The publishable key without a rule403. Every table is closed until a rule opens it.
A query on a branch that doesn't exist404.

Every write is recorded, so anything a query does can be rewound.

On this page