Skip to main content

Outputs

An output is a named emitter of generated files. Each output reads the same two inputs: the semantic model (entities, fields, relations, enums and indexes as the visitor role sees them) and the query plans (one plan for each query the rules select).

Output directory​

Each output writes into the configured outputDir. By default the files of each table sit in <schema>/<table>/, and the names below are the files in that folder. Import the generated files from that directory. You can edit them. The generator merges new declarations and schema changes with your edits on each run.

The hashes and import names from the last run live in outputDir/.pg-sourcerer/manifest.json. Commit this manifest with your code. Files outside the manifest and the new output belong to you and remain untouched.

When both sides change a declaration differently, the output file gets two-way conflict markers. The manifest stores hashes rather than old source, so even edits on separate lines of that declaration conflict. The CLI lists each conflicted file and declaration and exits with code 1. Resolve the markers before the next run. The manifest already records the new pristine output.

effect​

TypeScript for Effect 4.

  • schemas.ts: one Schema.Struct for each row, insert and update shape, and Schema.Literals for each enum.
  • queries.ts: one function for each plan. It runs SQL through SqlClient.
  • errors.ts: NotFound (HTTP 404) and StoreFailure (HTTP 500). The classes carry no SQL text.
  • rpc.ts: one RPC for each query and a handler layer.
  • http.ts: one HttpApiGroup for each entity and a handler layer for each group.

effectApp​

effectApp(options) is the effect plugin plus a server you can run. It takes the options of effect(...) and passes them on. List it in place of effect():

plugins: [effectApp()]

It adds two files to the effect files. Both are scaffolds: edit them freely, and the merge keeps your edits on later runs.

  • server.ts: ApiLive serves the generated Api with the handler layer of every group. SqlLive is an @effect/sql-pg client configured from Config.Redacted("DATABASE_URL"). AppLive adds the OpenAPI document at /openapi.json and the Scalar docs page at /docs, and gives the routes SqlLive. Each is its own declaration, so to change one you edit one.
  • main.ts: serves AppLive with the Bun HTTP server on Config.Port("PORT"), default 3000, and runs it with BunRuntime.runMain.

The app needs @effect/platform-bun and @effect/sql-pg next to effect. To run it:

DATABASE_URL=postgres://user@localhost/app bun main.ts

SqlLive registers a codec for timestamp and timestamptz, so those columns arrive as the ISO text the schemas declare. PgTypesLive is that codec; edit it to register more types.

kysely​

  • kysely/db.ts: one interface for each table and a DB interface keyed by schema.table.
  • kysely/queries.ts: one function for each plan. It takes a Kysely<DB> and returns a query.

types​

types.ts holds plain interface row, insert and update types, and a string union for each enum. Each type has the same fields as the effect schema of the same name, so Users equals typeof Users.Type.

hono, express, elysia, trpc and orpc​

Each writes one routes file (hono.ts and so on) that calls the query functions of the queries output (default kysely). Options:

  • queries: the output that declares the query functions.
  • validator: "zod", "valibot" or "arktype", to validate request bodies.
  • basePath (hono, express, elysia, and effect for its HttpApi): a prefix for every route, for example hono({ basePath: "/api" }) serves /api/users/:id. It holds literal segments only. trpc and orpc do not take it, because the app chooses where to mount their routers.
  • schemas: the schemas whose tables get routes, for example hono({ schemas: ["app_public"] }). The default is every schema with a generated query. A schema the catalog does not have fails the run.

trpc and orpc take the app's own base, so its context and middleware apply to every route. orpc.ts exports orpcRouter(base, db), where base is os or os after .use(), and it returns the router. trpc.ts exports trpcProcedures(procedure, db), where procedure is the app's base procedure, and it returns the procedures for t.router(...), because only the app's t can build a router.

The two signatures, as the generated files declare them:

export const orpcRouter = (
base: Pick<BuilderWithMiddlewares<any, any, any, any, any, any>, "input" | "handler">,
db: Parameters<typeof deleteCommentsById>[0]
) => ({
// ...
});
export const trpcProcedures = (
procedure: TRPCProcedureBuilder<any, any, any, TRPCUnsetMarker, TRPCUnsetMarker, TRPCUnsetMarker, TRPCUnsetMarker, false, any>,
db: Parameters<typeof deleteCommentsById>[0]
) => ({
// ...
});
const t = initTRPC.context<Context>().create()
const appRouter = t.router(trpcProcedures(t.procedure.use(requireUser), db))

A table path is /<table>, for example /users/:id. When two routed tables share a name in different schemas, each path starts with its schema: /app-public/users/:id and /app-private/users/:id. The generator counts the collision among the tables the output routes, so schemas: ["app_public"] gives /users/:id. The effect output's http.ts routes every schema.

openapi and client​

Both read the same route model as the transports, so a path, method, parameter, body, status and "row not found" answer is the one the routes serve. Both require routes, which they add themselves. client also requires types(). Options, with the meaning and defaults they have for the transports:

  • basePath: a prefix for every path, for example openapi({ basePath: "/api" }).
  • schemas: the schemas whose tables and functions are described.

openapi() writes openapi.json, an OpenAPI 3.1 document of every route. Paths sort by path then method, and components by name, so equal schemas give equal text. Component schemas describe the row, insert and update shape of each routed table, the result record of a function, and the enums and domains they name. A field's schema follows the same classification as the validator outputs: a CHECK list of literals becomes an enum, and length, pattern and bound rules become the matching keywords. A case-insensitive pattern has no JSON Schema form and adds no keyword. A bytea column has no agreed JSON form and gets an empty schema.

client() writes client.ts, plain TypeScript with no runtime dependency:

const api = createClient("https://api.example.com")
const user = await api.findUsersById({ id }) // Users | undefined
const post = await api.insertPosts({ body: "hello" }) // Posts
const edited = await api.updatePostsById({ id }, { body: "edited" })

createClient(baseUrl, fetchFn = fetch) returns one function per route, named by the route's query. A route with path or query parameters takes them as the first argument, and a route with a body takes the body last. Each type comes from types.ts. A 2xx answer resolves to the decoded JSON, or to undefined for 204. A route that answers 404 for a missing row resolves to undefined. Any other non-2xx answer rejects with ClientError, which holds status and the response body text.

react​

react() writes React components that render the rows of each table or view that has routes. It requires routes and types(), which it adds itself, and it needs react in the project that imports the output. It takes the schemas option, with the meaning it has for the transports. The components are unstyled semantic HTML with no CSS and no class names, and they fetch nothing: they take their data as props, so a router that loads the data can mount them. The file is react.tsx, so the default layout writes <schema>/<table>/react.tsx.

Each view exists only when the routes of the entity allow it:

ComponentExists when the entity hasProps
UsersLista list routerows: readonly Users[], onSelect?: (row: Users) => void
UsersDetaila find-by-key routerow: Users
UsersCreateForman insert routeinitial?: Partial<UsersInsert>, onSubmit: (value: UsersInsert) => void | Promise<void>
UsersUpdateForman update routeinitial: Partial<UsersUpdate>, onSubmit: (value: UsersUpdate) => void | Promise<void>

The list is a table with one column per field, and onSelect puts a button in the first cell of each row. The detail view is a definition list. A form has one labelled input per field of the insert or update body. The input follows the field's type: a text input for text, a number input for numbers, a checkbox for booleans, a date or datetime-local input for date and timestamp columns, a select for an enum or a CHECK list of literals, and a textarea for json and jsonb. A form keeps its input state in useState and converts it to the field's type on submit, so a number field submits a number. An empty nullable field submits null, an empty field that the body may omit is left out, and a required field has the required attribute. bigint and numeric columns stay strings, as in the types output.

A bytea or array column has no input, so a form leaves it out and says so in a comment. A create form whose body needs such a column cannot build a value of its type, so that form is not written.

Each component has an exported <Name>Props type. The names come from the componentName inflector. Another output imports a component through reactCapability, which the pg-sourcerer package exports; see "Capabilities of the react output" in the authoring guide.

solid​

solid() writes the views react() writes, as Solid components: per entity, the same List, Detail, CreateForm and UpdateForm under the same rules, with the same props and the same exported <Name>Props types. It requires routes and types(), which it adds itself, and it needs solid-js in the project that imports the output. It takes the schemas option, with the meaning it has for the transports. The components fetch nothing and mount no router: they take their data as props. The file is solid.tsx, so the default layout writes <schema>/<table>/solid.tsx.

The markup is the markup react() writes. The code follows Solid's rules for reactivity: a component reads props.rows where it uses it and never destructures its props, the list renders its rows with <For>, and the select button of a row appears through <Show when={props.onSelect}>. A form keeps its input state in one createStore object, so the submit step reads draft.<field> and each input writes its own field from onInput. Field ids come from createUniqueId. The submit rules are the rules of react(): an empty nullable field submits null, an empty field that the body may omit is left out, and text that is not JSON in a json field stops the submit.

Solid's JSX needs Solid's compiler. A project that imports solid.tsx sets "jsx": "preserve" and "jsxImportSource": "solid-js" in its tsconfig.json and compiles with babel-preset-solid or a bundler plugin that uses it. The generator checks a file that imports solid-js against Solid's JSX types, and every other .tsx file against React's. Another output imports a component through solidCapability, which the pg-sourcerer package exports; its ids are solid:<view>:<Entity>, and its props are those in "Capabilities of the react output" in the authoring guide.

tanstackRouter​

tanstackRouter() writes a code-based TanStack Router tree that mounts the components react() writes. It requires routes, react() and client(), which it adds itself, and it needs @tanstack/react-router in the project that imports the output. It takes the schemas and validator options, with the meaning they have for the transports. The router owns the data: each loader calls the generated client, and each form calls a client mutation.

It writes three kinds of file. router/root.tsx holds RouterContext ({ client: Client }) and rootRoute, built with createRootRouteWithContext, so a loader reads the client from the router context and never from a module-level instance. <schema>/<table>/tanstack-router.tsx holds one route object per page of that table. router/tree.tsx holds routeTree, which adds every page to rootRoute. The files import each other in one direction, so there is no import cycle.

Each page exists only when the routes of the table and the react() components it needs exist:

PagePathLoader and behaviour
list/usersCalls the first list route that is ordered by key, with the cursor and limit from the URL (limit 50 when the URL has none). Renders UsersList. onSelect opens the detail page. A link goes to the new page. A full page also shows a Next link, and a page with a cursor shows a First link.
detail/users/$usernameCalls the find-by-key route with the path params. A row that is not there throws notFound(). Renders UsersDetail, a link to the edit page, and, when the table has a delete-by-key route with the same key, a Delete button.
new/users/newRenders UsersCreateForm. On submit it awaits the insert, then router.invalidate(), then goes to the list.
edit/users/$username/editLoads the row as the detail page does. Renders UsersUpdateForm with initial set to the row. On submit it awaits the update, invalidates the router, then goes to the detail page.

The path segment is the table's segment in the HTTP routes. A key gets one $param per column. The detail page uses the find-by-key route that an update route shares its key with, so the edit page has the same URL shape; without such a pair the table has a detail page and no edit page. A key that is a number or a boolean is converted from the URL string by params.parse and back by params.stringify.

You build the router with the client in its context:

import { createRouter } from "@tanstack/react-router"
import { createClient } from "./client.js"
import { routeTree } from "./router/tree.js"

const router = createRouter({ routeTree, context: { client: createClient("https://api.example.com") } })

The Delete button asks window.confirm("Delete this row?"). On yes it awaits the client's delete function, then router.invalidate(), then goes to the list page. When the table has no list page the detail page stays put, and its reloaded loader shows the not-found state.

Every page that writes (new, edit and the Delete button) catches the ClientError the client rejects with, such as a 400 from a CHECK constraint, a 409 or a failed request, and shows its message in a <ul role="alert"> above the form (after the Delete button on the detail page). The page stays where it is. Any other error is rethrown. The components react() writes are unchanged: the page holds the messages, so the forms take no error prop.

With tanstackRouter({ validator: zod() }), the new and edit pages also check the form value with the validator's insert or update schema (its Standard Schema ~standard.validate) before they call the client. When the schema reports issues, the page shows one message per issue, <path>: <message> (the message alone when the path is empty), and sends nothing. The validator must write Standard Schema schemas, as the validator of a transport must. Without a validator the pages send the value as it is and show only server errors. The issue messages come from router/issues.ts, which exists only when a validator is set.

The list page keeps its paging state in the URL, as search params: the keyset cursor (one param per cursor column, named as in the list route) and limit. validateSearch is a plain function that reads each value by its kind; an absent or malformed value is dropped, so ?limit=abc loads the default page. loaderDeps passes the search to the loader. A full page (as many rows as the limit) shows a Next link whose search holds the last row's cursor values and the same limit. A page with a cursor shows a First link that drops the cursor. There is no Previous link, because a keyset page has no cheap way back. Only the list page has search params.

The route and page names are <Component>Route and <Component>Page, where the component name comes from the componentName inflector (UsersListRoute, UsersCreateFormRoute). Other outputs import a route through tanstackRouterCapability; see the authoring guide.

suggestion-report​

query-suggestions.json lists the queries the generator could produce and the reasons it rejected the others. It is not part of webApp().

Query rules and smart tags​

Which queries exist depends on the grants and policies of the visitor role. You can narrow the set with smart tags: comments on tables and columns that start a line with @omit or @name.

comment on table app_public.comments is '@name Reply';
comment on column app_public.comments.id is '@omit update,delete';
comment on domain app_public.ticket_number is '@brand';

On a domain, @brand makes the domain a nominal type and @brand false keeps it plain, whatever the domains.brand default in the config says. The config equivalent is a tags.type rule with brand, which wins over the tag. Every tag has such a config form; see the tags field in config.

The authoring guide lists every tag and what it does.

byKind​

By default each table's symbols go to their own folder: <schema>/<table>/<file>, for example app_public/users/schemas.ts. Symbols that serve every entity stay at the root: the kysely DB interface, the error classes, the HTTP Api and its handlers, the transports, client.ts and openapi.json.

byKind() opts out. It changes where files go, not what they hold: every table's symbols share one file for each kind, for example schemas.ts. List it beside the other plugins:

plugins: [webApp(), byKind(), types(), zod()]

Switching layouts moves files. The merge publish keys its manifest by path, so files appear at the new paths. Edits you made in the files at the old paths stay where they are.

Write your own​

An output is an Effect value in two phases: it declares symbols, then it links the imports between them. The authoring guide builds one step by step. Conjure builds the statements.