Configuration
A project is one value: where the catalog comes from, which role runs the code, where the files go and which plugins to run. Put it in pgsourcerer.config.ts. The CLI looks in the current directory and in every parent directory, and uses the nearest file.
import { defineConfig, fileSource, webApp } from "pg-sourcerer"
export default defineConfig({
source: fileSource("./introspection.json"),
visitorRole: "visitor",
outputDir: "./src/db",
plugins: [webApp()],
format: ["bunx", "oxfmt"],
})
Fields
-
source:fileSource(path)reads a JSON file that holds either the raw result of the introspection query or a catalog snapshot.connectionSource(url)runs the introspection query on a live database. The URL is aRedactedvalue, so logs do not show it. -
visitorRole: the role the generated code runs as. The role must exist in the catalog. -
outputDir: the directory that receives the files. You can edit any generated file. Each run merges the new output with your edits against hashes from the previous generation in.pg-sourcerer/manifest.json. Commit this manifest with your code. A declaration both sides changed gets a conflict, even when the edits affect separate lines. -
plugins: a list of plugins.effect(),kysely(),types()andsuggestionReport()each build one. A plugin also runs the plugins it requires, so list only the ones you want generated:hono()runskysely()for its queries, andsqlQueries()andtypia()runtypes().webApp()is a plugin that requireseffect()andkysely(). When your list holds a plugin of the same name as a required plugin, yours is the one that runs. A transport takes the plugins it calls as options:hono({ queries: sqlQueries(), validator: zod() }). The files of each table go in<schema>/<table>/; listbyKind()to keep one file for each kind instead. -
format(optional): a formatter command as an argv list, for example["bunx", "oxfmt"]. The generator appends the directory of the generated files and runs it before it validates and hashes the result. -
domains(optional):{ brand?: boolean }, default{ brand: false }. A PostgreSQL domain becomes a named type in every output, with a validator for the CHECK rules the generator can read (length bounds, numeric bounds, regular expressions). A branded domain is nominal, so a plainstringdoes not satisfyUsername:types()andkysely()intersect the base type with a~brandmarker, and each validator library applies its own brand (Schema.brand, zod.brand(), valibotv.brand(), arktype.brand()).brandis the default for every domain. A domain's@brandsmart tag wins over it, and thetags.typerule of the domain, for exampletags: { type: { "app_public.ticket_number": { tags: { brand: false } } } }, wins over both. A domain that is not branded still gets a named type, such astype TicketNumber = number. Thetypiaoutput cannot validate branded types, so it fails when any domain is branded. A CHECK rule outside the readable set is listed underdomainsinquery-suggestions.jsonand stays enforced by the database only. -
tags(optional): smart tags and descriptions that take the place of PostgreSQL comments. Rules are grouped underclass(tables and views),attribute(columns),procedure(functions) andtype(domains), keyed bynameorschema.name. Each rule is{ tags?, description? }, and aclassrule may nest its columns underattribute. The tag values are the text of a comment tag:{ tags: { omit: "read, create", name: "Purchase" } }. A rule's tags win over the comment's tags of the same name, and a rule that matches nothing fails the run. See the authoring guide. -
inflection(optional): one override object, or a list of them, that changes how generated code is named. See Naming.
Relative paths resolve against the directory of the config file.
Naming
Each name in generated code comes from an inflector: a function from a catalog object to a name. inflection replaces some of them. An override receives the inflector it replaces, the input and a set of case helpers, and returns the name. A list applies in order, so each override sees the result of the ones before it.
import { defineConfig, fileSource, keepNames, webApp } from "pg-sourcerer"
export default defineConfig({
source: fileSource("./introspection.json"),
visitorRole: "visitor",
outputDir: "./src/db",
plugins: [webApp()],
inflection: [
// Keep `created_at` as `created_at` in every shape, parameter and result.
keepNames,
// `findUsersById` becomes `getUsersById`; the transports import the new name.
{ queryName: (previous, input) => previous(input).replace(/^find/, "get") },
],
})
The inflectors are entityTypeName, qualifiedTypeName, enumTypeName, domainTypeName, shapeTypeName, fieldName, queryName, requestTypeName, resultTypeName, functionName, handlerGroupName, handlerLayerName, componentName and routeSegment. A key that names none of them fails the config load.
fieldNamereceives{ schema, table, column }. WithkeepNamesthe generated selects need noas "createdAt"alias.queryNamereceives{ kind, entityTypeName, fields, order, qualified }, wherekindis the candidate kind such asfind-by-key,fieldsare the resolved field names of the key columns,orderlists the order columns of alist-by-indexquery as{ field, direction }, andqualifiedis true when another query shares the key, so the name must say how it orders.- The third argument of an override is
{ pascalCase, camelCase, kebabCase }. routeSegmentreceives{ schema, table, column, name, qualified };columnis absent for a table.qualifiedis true for a table whose name another routed table shares in another schema; the default then returns<schema>/<table>, for exampleapp-public/users. If an override gives two tables one method and path, the run fails.
A @name smart tag (or the name tag of a tags rule) on a table or column is the final name for that object, and its inflector does not run. The generator checks every name. A name that is not a valid identifier, a reserved word where a binding is needed, or a name used twice in one file fails the run with a NamesError that names the inflector, the table or column, and the result.
Flags
The CLI accepts --input <file>, --connection <url>, --plugins <names> and two optional positional arguments, [output] [visitor-role]. Each one replaces the matching config field. With no config file, the CLI reads the source from --input, --connection or DATABASE_URL.
In the browser
The browser entry, pg-sourcerer/browser, has no file system and no config loader. Give it an SQL executor and read the documents:
import { Effect } from "effect"
import { DatabaseSnapshot, generateDocuments, webApp } from "pg-sourcerer/browser"
// Any object with this shape: PGlite, a proxy to a server, or a test fixture.
declare const db: { query(sql: string, params: unknown[]): Promise<{ rows: any[] }> }
const snapshot = DatabaseSnapshot.fromExecutor(async (sql, params) => (await db.query(sql, [...params])).rows)
const { files } = await generateDocuments("visitor", [webApp()]).pipe(
Effect.provide(snapshot),
Effect.runPromise,
)
db is any object that runs SQL and returns rows. The playground on the home page does exactly this inside a web worker.