Roc Solid
Markup in Roc · pages on a native server · components in WebAssembly

The ecosystem · packages/admin

An admin for your tables, read from the database itself

A Django-style admin: see and fix your data without building pages for it. Each table gets a page of rows with a search, a filter in every column, sorting and pages, and a form to add, change or delete a row. The admin reads your tables from the database's catalog (Postgres or SQLite) on each request: no code to generate, nothing to keep in step with your schema.

Mount it with one route file, behind your app's middleware. The package also draws the jobs page, the queue of packages/jobs, on a route file of yours too.

Installing it#

Name the package in your app's header (main.roc) by its directory's name, as the docs site does:

site/main.roc
app [program] { admin: "../packages/admin/main.roc", …, pf: platform "../server/platform/main.roc", … }

The package names the server platform (for the jobs page), so its pf must be your app's platform file. The admin runs only on the server: nothing in the browser imports a +server.roc, so the browser's half never compiles it.

A first admin#

Add a route file at the admin's path: routes/admin/db/+server.roc is /admin/db. Its respond! hands every request to AdminPage.respond! with:

site/Demos/AdminRoute.rocx
import pf.Db
import pf.Random
import pf.Server
import admin.Admin
import admin.AdminPage

## An admin, as an app writes it in a route file (`routes/admin/db/+server.roc`), behind the
## middleware that says who is asking (`routes/admin/+middleware.roc`: `middleware =
## Middlewares.staff`). Here it is a module of the
## docs site, so the compiler checks it with the site's server; no route answers with it, since the
## site has no database.
AdminRoute := [].{

	## Who is asking, as the route's middleware hands it on.
	Who : { user : Str, staff : Bool }

	## Where the admin is, who may use it, and which tables it shows, how.
	admin : Admin.Config(Who)
	admin = {
		mount: "/admin/db",
		access: |who| if (who.staff) Edit else Refused,
		tables: [
			{ name: "books", list: ["id", "title", "author_id", "state", "price"], search: ["title", "blurb"], ordering: ["-id"] },
			{ name: "authors", title: "name", hidden: ["password_hash"], labels: [("email", "Email address")] },
		],
	}

	## The route's answer: the request, handed to the admin with the effects it runs on.
	respond! : { request : Server.Request, params : {}, context : Who } => Server.Response
	respond! = |{ request, context, .. }| AdminPage.respond!(request, context, AdminRoute.admin, { all!: Db.all!, run!: Db.run!, random!: Random.bytes!, backend!: Db.backend! })
}

In your app these go in the route file. Here they are a module the compiler checks, but nothing answers with them: the docs site has no database.

What it looks like#

The package's View rendered these with this page, from a made-up catalog (books and authors) and the options above. No database is asked, and the frames are sandboxed: links and forms do nothing. Like the jobs page, they use the admin look: tables in a sidebar (across the top when narrow), a header with the page's actions, panels, and light or dark to match your system.

A table's rows, filtered to a price of 10 or more, a filter under each heading. A heading sorts, the search looks in title and blurb, and a foreign key links to its row.
A row's form, just saved, with a widget for each column's type. The key is shown, not editable.
The made-up tables, and the pages rendered from them: site/Demos/AdminPreview.rocx
site/Demos/AdminPreview.rocx
import admin.Admin
import admin.Catalog
import admin.Form
import admin.Listing
import admin.Look
import admin.Paging
import admin.Sql
import admin.View
import AdminRoute

## The admin's pages as the docs show them: rendered with the page, by the package's own `View`,
## from a made-up catalog (what Postgres's would say of two tables, `books` and `authors`) and
## made-up rows, with the options the docs show (`AdminRoute.admin`). Nothing here asks a database.
AdminPreview := [].{

	## The list of books with a filter on, `price` from 10, as a whole HTML document, for a
	## sandboxed frame: the made-up rows it keeps, and their count.
	list_page : Str
	list_page = {
		state = Listing.read(books, Form.fields("table=books&from.price=10"))
		kept = book_rows.keep_if(|each| (Dec.from_str(Catalog.cell(each, 4)) ?? 0) >= 10)
		body = View.list_page(frame, { shown: books, state, page: Paging.of(kept.len(), 8, 1), rows: kept, notice: "" })
		framed(Look.document("Books · Database", View.side(frame, Table("books")), body))
	}

	## A book's form, just saved, as a whole HTML document.
	row_page : Str
	row_page = {
		values = [
			("id", "21"),
			("author_id", "3"),
			("title", "A field guide to clouds"),
			("state", "published"),
			("price", "24.90"),
			("in_print", "true"),
			("published_at", "2026-03-14T09:30:00"),
			("blurb", "Cumulus, stratus and the rest,\nwith a chapter on fog."),
		]
		body = View.row_page(
			frame,
			{
				shown: books,
				key: [("id", "21")],
				values: values.map(|(name, value)| { name, value, null: Bool.False }),
				options: [{ column: "author_id", options: [("3", "Ines Hart"), ("1", "Mara Quill"), ("2", "Tomas Reed")] }],
				problem: "",
				notice: View.notice("saved"),
			},
		)
		framed(Look.document("A field guide to clouds · Database", View.side(frame, Table("books")), body))
	}

	## The query the statements are for.
	query : Str
	query = "table=books&q=cloud&f.state=published&from.price=10&sort=-price&page=2"

	## The two statements the list runs for `query`: how many rows there are, then the page's.
	statements : Str
	statements = {
		state = Listing.read(books, Form.fields(AdminPreview.query))
		conditions = Listing.conditions(books, state)
		count = Sql.count({ schema: "public", dialect: Postgres }, books.table, conditions)
		page = Paging.of(120, books.options.per_page, state.page)
		rows = Sql.rows(
			{ schema: "public", dialect: Postgres },
			books.table,
			{ columns: Admin.listed(books), whole: Admin.key(books), conditions, order: Listing.order(books, state), limit: page.size, offset: Paging.offset(page), longest: 81 },
		)
		Str.join_with(["-- How many rows there are", said(count), "", "-- The page's rows (the count said 120)", said(rows)], "\n")
	}
}

## A row as the catalog's statements answer it.
row : List(Str) -> Catalog.Row
row = |cells| { cells, nulls: [] }

## Two tables, as `Catalog.read` gets them from Postgres: the tables, their columns, their enums'
## labels, and their keys and checks.
catalog : List(Catalog.Table)
catalog =
	Catalog.read(
		"public",
		{
			tables: [row(["authors", "3", "People who write books"]), row(["books", "23", ""])],
			columns: [
				row(["authors", "id", "bigint", "int8", "N", "false", "true", "false", "", ""]),
				row(["authors", "name", "text", "text", "S", "false", "false", "false", "", ""]),
				row(["authors", "email", "character varying(120)", "varchar", "S", "true", "false", "false", "Where to reach them", ""]),
				row(["authors", "password_hash", "text", "text", "S", "true", "false", "false", "", ""]),
				row(["books", "id", "bigint", "int8", "N", "false", "true", "false", "", ""]),
				row(["books", "author_id", "bigint", "int8", "N", "true", "false", "false", "", ""]),
				row(["books", "title", "text", "text", "S", "false", "false", "false", "", ""]),
				row(["books", "state", "text", "text", "S", "false", "true", "false", "", "'draft'::text"]),
				row(["books", "price", "numeric(10,2)", "numeric", "N", "false", "true", "false", "", "0"]),
				row(["books", "in_print", "boolean", "bool", "B", "false", "true", "false", "", "true"]),
				row(["books", "published_at", "timestamp with time zone", "timestamptz", "D", "true", "false", "false", "", ""]),
				row(["books", "blurb", "text", "text", "S", "true", "false", "false", "What the back cover says", ""]),
			],
			enums: [],
			constraints: [
				row(["authors", "authors_pkey", "p", "id", "", "", "", "1", "PRIMARY KEY (id)"]),
				row(["books", "books_author_id_fkey", "f", "author_id", "authors", "public", "id", "1", "FOREIGN KEY (author_id) REFERENCES authors(id)"]),
				row(["books", "books_pkey", "p", "id", "", "", "", "1", "PRIMARY KEY (id)"]),
				row(["books", "books_state_check", "c", "state", "", "", "", "1", "CHECK ((state = ANY (ARRAY['draft'::text, 'published'::text, 'out of print'::text])))"]),
			],
		},
	)

## The tables the docs' admin shows, with its options.
shown_tables : List(Admin.Shown)
shown_tables = Admin.showing(AdminRoute.admin, catalog)

books : Admin.Shown
books = Admin.find(shown_tables, "books") ?? Admin.pair({ name: "books", comment: "", estimate: 0, columns: [], key: [] }, { name: "books" })

## What each page knows: the admin's path, someone who may edit, and a form's token.
frame : View.Frame
frame = { mount: AdminRoute.admin.mount, title: AdminRoute.admin.title, tables: shown_tables, access: Edit, token: "3f9c0e7a51d24b8e9a6c2d417b0e85f1", back: AdminRoute.admin.back, to_app: "" }

## The first page of books, as `Sql.rows` reads them: the listed columns, then the key.
book_rows : List(Catalog.Row)
book_rows =
	[
		["23", "The quiet garden", "1", "published", "18.50"],
		["22", "Notes on rivers", "2", "draft", "12.00"],
		["21", "A field guide to clouds", "3", "published", "24.90"],
		["20", "Small machines", "1", "out of print", "9.99"],
		["19", "The long winter", "", "draft", "15.00"],
		["18", "Maps of nowhere", "2", "published", "21.00"],
		["17", "Bread and salt", "3", "published", "14.25"],
		["16", "Letters from the coast", "1", "draft", "0.00"],
	].map(|cells| { cells: cells.append(cells.first() ?? ""), nulls: cells.map(|cell| cell.is_empty()).append(Bool.False) })

## A page in a frame of its own: its links open nowhere (a sandboxed frame opens no window).
framed : Str -> Str
framed = |document| document.replace_first("<head>", "<head><base target=\"_blank\">")

## A statement and its parameters, as SQL and a comment.
said : Sql.Statement -> Str
said = |statement| {
	params = statement.params.map_with_index(|param, at| "$${(at + 1).to_str()} = ${param_text(param)}")
	sql = statement.sql.replace_each(" from ", "\nfrom ").replace_each(" where ", "\nwhere ").replace_each(" order by ", "\norder by ").replace_each(" limit ", "\nlimit ")
	"${sql}\n-- ${Str.join_with(params, ", ")}"
}

## A parameter as SQL would write it.
param_text : Sql.Param -> Str
param_text = |param|
	match param {
		Null => "null"
		Text(text) => "'${text.replace_each("'", "''")}'"
		Int(n) => n.to_str()
		Bool(yes) => if (yes) "true" else "false"
	}

expect AdminPreview.list_page.contains("<h1>Books</h1>") and AdminPreview.list_page.contains("1–6 of 6") and AdminPreview.list_page.contains("name=\"from.price\" value=\"10\"")
expect AdminPreview.row_page.contains("<h1>A field guide to clouds</h1>") and AdminPreview.row_page.contains("Saved.")
expect AdminPreview.statements.contains("\"price\" >= $3::numeric") and AdminPreview.statements.contains("-- $1 = '%cloud%', $2 = 'published', $3 = '10'")

Its pages#

Every page is the admin's path plus a query, so one route file is enough. A query can name only the tables and columns the app lets the admin show.

QueryPage
(none)the tables, each with its estimated row count (Postgres only), its comment, and a link to add a row
?table=books its rows, 50 a page (page=2), counted and paged by the database; a search (q=cloud), a filter in each column (has.title=cloud, from.price=10, f.state=draft, is.author_id=null: see Filters), and a sort (sort=title, or sort=-price for descending)
?table=books&k.id=21a row's form: k. plus each primary-key column, so two-column keys work too
?table=books&newa new row's form, with its constant defaults filled in (true, 'draft', 0)
?table=books&k.id=21&deletea confirmation, and the button that deletes the row

Sending a form adds, changes or deletes the row, then shows the row's page saying Saved. An update writes only changed columns. If the database refuses (a price that isn't a number, an author books still name), the form comes back with what you sent and the database's reason. A table without a primary key is listed, but its rows can't be opened.

Filters#

Each column a list shows gets a filter under its heading, chosen by its type; a hidden column never does. Filters can't be turned off: filtering a shown column reveals nothing a visitor can't already see. To filter by a column, list it.

ColumnFilterQuery
text, varchar, uuid, json and any other typethe text it contains, in any case; % and _ match themselveshas.title=cloud
a number: integer, bigint, numeric, real, …from, to, or both, inclusivefrom.price=10&to.price=20
date, timestamp, timestamptz (in UTC), timefrom, to, or both, inclusive, with the browser's pickersfrom.published_at=2026-03-01T00:00
booleana select: any, yes, nof.in_print=true
an enum, or a check that it is one of a few valuesa select of its valuesf.state=draft
a foreign keythe value it equalsf.author_id=3
any of these, if it may be nullalso empty and not empty: in its select, or in a small select under its inputsis.blurb=null, is.blurb=set

The filters are one GET form, no JavaScript: Enter in any of them, or the Filter button beside the search, sends it. Filtering keeps the search and sort and returns to the first page; page links and sorting keep the filters; Clear filters drops them all.

Each value is checked in Roc before it reaches SQL (a number for a number, 2026-03-14 for a date, one of an enum's labels), and a range's value is cast to its column's type ("price" >= $3::numeric). A wrong value is ignored and its filter says so (Ignored: not a number), so a bad query never makes the page an error.

Who may use it#

The route's middleware runs first, so it can send a stranger to sign in. Then access decides from the context it handed on:

access saysThen
Editevery page, and adding, changing and deleting rows
ReadOnlythe tables, rows and values; no forms
Refuseda 403, and nothing is read

A form's POST must come from the same site (its Origin header) and send back its page's token. The token lives in a cookie, rocx_admin_csrf: sent only to the admin's path, unreadable by scripts (HttpOnly), and not sent with another site's form (SameSite=Lax). Any other POST gets a 403 before a table is read.

Options#

Admin.Config(context) configures the admin. Only mount and access are required.

FieldWhat it is
mount : Strthe route's path
access : context -> [Edit, ReadOnly, Refused]what someone may do, decided from the middleware's context
tables : List(Admin.Table)the tables it shows, in order, with their options (none by default)
include : [Listed, All]Listed (the default) shows only those tables; All adds every other table of the schema, with default options, except the platform's own (rocx_…)
schema : Strthe Postgres schema: "public" by default (SQLite's is always main)
title : Strwhat its pages call it: "Database" by default
back : { label : Str, href : Str }a link to the app's pages, first in every sidebar ({ label: "Status admin", href: "/admin" }); none by default

Admin.Table holds a table's options, naming columns as the table does. A table or column the schema doesn't have stops the admin: its pages say what is wrong and show nothing else until it is fixed, since a misspelt hidden would show the column it should hide.

FieldDefaultWhat it is
name : Str(required)the table
label : Strits name, made readable: book_tags is Book tagswhat the pages call it
list : List(Str)its first seven columnsthe columns its list of rows shows, each with a filter
search : List(Str)no search boxthe columns searched, for the text anywhere, in any case
ordering : List(Str)its key, newest firstthe list's order; - for descending: ["-published_at", "title"]
read_only : List(Str)nonecolumns shown on the form, never written
hidden : List(Str)nonecolumns never read, shown or written, such as a password's hash
labels : List((Str, Str))each column's name, made readablewhat to call its columns: [("email", "Email address")]
title : Strits first text column that isn't its keythe column that names a row: the heading of its page, and its name in a foreign key's select
per_page : U6450rows a page
widgets : List((Str, Widget.Kind))the column's type'sanother input for a column: [("body", LongText)]
create : Bool, delete : Boolyeswhether rows may be added or deleted

Widgets#

A widget is a column's input on a row's form, chosen from the column's type in the catalog (for a domain, its base type):

ColumnWidget
a foreign key to a table the admin showsa select of that table's rows, by their title (an input, when there are more than 200), and a link to the row
an enum, or a check that it is one of a few values (check (state in ('draft', 'published')))a select of them
booleana checkbox; a select of yes, no and null when it may be null
smallint, integer, biginta number
numeric, real, double precisiona decimal's input
date, timestamp, timestamptz, timethe browser's pickers; a timestamptz in UTC
json, jsonba text area, in a monospace font
text, varchar(n), uuid and the restan input (with maxlength for a varchar(n)), or a text area for a value of several lines; the database reads what is typed as the column's type
a generated column, byteashown, never written

An empty input is null where the column allows it, else an empty text for a text column. In a new row, an empty input leaves a column's default to the database. To change a column's widget, name it in the table's widgets; the README lists every Widget.Kind.

How it works#

On each request, the admin reads the schema from the catalog into tables (Catalog.read): columns and types, which may be null or have defaults, primary and foreign keys, enums, and the values a check allows. On Postgres that is four small statements over pg_catalog. On SQLite it reads pragma_table_list, pragma_table_xinfo and pragma_foreign_key_list, and each table's checks from its create table. A SQLite type is read as Postgres would name it (integer as int8, boolean as bool), so it gets the same widget and filter.

A table or column a request names is looked up there, among those the app lets the admin show. Only the catalog's names go into SQL, double-quoted; every value is a parameter:

packages/admin/Sql.roc, in part
## A name as SQL writes one, in double quotes: `"order"`, `"say ""hi"""`. Any text is safe in
## them but a zero byte, which Postgres's names can't hold, and which is dropped.
ident : Str -> Str
ident = |name| "\"${Str.from_utf8_lossy(name.to_utf8().keep_if(|byte| byte != 0)).replace_each("\"", "\"\"")}\""

## A table in a schema: `"public"."users"`.
qualified : Str, Str -> Str
qualified = |schema, table| "${Sql.ident(schema)}.${Sql.ident(table)}"

## A text as `ilike` (and SQLite's `like … escape '\'`) finds it anywhere in another: `%`, `_`
## and `\` in it stand for themselves.
contains : Str -> Str
contains = |text| "%${text.replace_each("\\", "\\\\").replace_each("%", "\\%").replace_each("_", "\\_")}%"

A list is two statements built by Sql: a count, then the page's rows. These are the statements for ?table=books&q=cloud&f.state=published&from.price=10&sort=-price&page=2 above, built as this page rendered:

?table=books&q=cloud&f.state=published&from.price=10&sort=-price&page=2
-- How many rows there are
select array_to_json(array[count(*)::text])::text as "cells", '[]'::text as "nulls"
from "public"."books"
where ("title" ilike $1 or "blurb" ilike $1) and "state" = $2 and "price" >= $3::numeric
-- $1 = '%cloud%', $2 = 'published', $3 = '10'

-- The page's rows (the count said 120)
select array_to_json(array[left(coalesce("id"::text, ''), 81), left(coalesce("title"::text, ''), 81), left(coalesce("author_id"::text, ''), 81), left(coalesce("state"::text, ''), 81), left(coalesce("price"::text, ''), 81), coalesce("id"::text, '')])::text as "cells", array_to_json(array["id" is null, "title" is null, "author_id" is null, "state" is null, "price" is null, "id" is null])::text as "nulls"
from "public"."books"
where ("title" ilike $1 or "blurb" ilike $1) and "state" = $2 and "price" >= $3::numeric
order by "price" desc, "id"
limit $4 offset $5
-- $1 = '%cloud%', $2 = 'published', $3 = '10', $4 = 50, $5 = 50

Every statement answers rows of one shape, each cell as text plus whether it was null (Catalog.Row), so one Db.all! reads any table. The database cuts a list's cells to 81 characters, so the page can tell one was cut; a key is never cut.

Pages go out with Content-Security-Policy: default-src 'none' (no script, nothing loaded from elsewhere, forms sent only to this site), X-Frame-Options: DENY and Cache-Control: no-store, and every value is escaped.

The jobs page#

The queue of packages/jobs also goes on a route of yours. Put its route file in your admin pages' folder, so that folder's middleware decides who sees it, and give mount the route's path:

routes/(admin)/admin/jobs/+server.roc
import admin.JobsPage

respond! = |{ request, .. }| JobsPage.respond!(request, { mount: "/admin/jobs", back: { label: "Status admin", href: "/admin" } })

A request passes the app's middleware, then the folder's, then the page, which needs the jobs plugin listed. back works as the tables admin's option does (none by default). The jobs page's own section says what it shows and does.

The tables admin, the jobs page and the dev mailbox of packages/email share one look (Look, and AdminHtml on it). Each sidebar ends with Back to the app: to the app page the reader came from (kept in a cookie until the browser closes, so the page's filters and forms keep it), or to the front page, /, when they came from nowhere (a typed address, a bookmark) or another site. The stories catalog has it too.

The modules#

AdminPage is the one module with effects: those your route hands it. JobsPage and AdminHtml run on the server platform. The rest is plain Roc on no platform; roc test packages/admin/main.roc runs their expects.

ModuleWhat it does
Adminthe options (Config, Table, Access), what they name that the schema doesn't have (problems), and what they mean for a table: showing, listed, searchable, writable, title, ordering, widget
AdminPagerespond!(request, context, config, effects): the access check, the token, the catalog, then the page or the form
Catalogthe statements that read the schema, on Postgres or SQLite, and read (read_sqlite), their rows as tables
Sqlident, contains (a search's or a filter's pattern), the conditions a list's rows meet, and the statements: rows, count, one, insert, update, delete, titles
Widgeta column's widget from its type (of), its input (input), what a form's text writes (param), whether it changed (same), a new row's value (initial)
Listinga list's search, filters, sort and page, read from the query and written back (read, params, conditions, order, key); each column's filter (kind) and the check of its values (check)
Pagingof(total, size, asked), offset, shows, links: the first two pages, three each side of this one, the last two
Vieweach page's HTML: index_page, list_page, row_page, delete_page, problem_page, problems_page, and the sidebar (side)
Lookthe admin look: the rules every admin page shares (shared) and its helpers (side, header, panel, empty, icon, button_with), light and dark; the tables admin's own rules, its document, and the headers it is sent with
Forma query's or a form's fields, decoded, and links, encoded
JobsPagethe jobs page: respond!(request, { mount, back }), from a route of the app's (server only)
AdminHtmlthe server's admin pages (the jobs page, the dev mailbox), on Look: a page with its stream of changes, times, links (server only)

Not yet#

Everything above works on Postgres and SQLite, tested over HTTP on both: the index, a new row's form, a row created, found by search and filter, changed and deleted. Not yet:

The package's README is the full reference, with its proposals beside it in packages/admin/. The pages and code above are the package's own.