Column Types
Every q.* column type — typed and indexed JSON, per-key write authority, decimals, dates, 64-bit integers, arrays — and the naming convention.
The column types available in feature() and defineTable() columns, how each maps to SQLite (D1) and PostgreSQL, and how column names map to SQL. Start at Database Schema for the table forms.
Column Types
| Builder | Drizzle equivalent | Zod type |
|---|---|---|
q.text() | text(...) | z.string() |
q.url() | text(...) | z.string().url({ protocol: /^https?$/ }) |
q.secret() | text(...) (envelope-encrypted, never returned) | z.string() — see Secret columns |
q.int() | integer(...) | z.number().int() |
q.bigint() | bigint(..., { mode: 'number' }) | z.number().int() within ±(2^53 − 1) |
q.smallint() | smallint(...) | z.number().int() within −32768..32767 |
q.decimal({ precision, scale }) | numeric(..., { precision, scale }) | decimal string within precision/scale |
q.bool() | boolean(...) | z.boolean() |
q.uuid() | uuid(...) | z.string().uuid() |
q.timestamp() | timestamp(...) (converted to SQLite text on sqlite targets) | z.coerce.date() |
q.date() | date(...) | z.iso.date() (YYYY-MM-DD) |
q.json() / q.json(z.object({...})) | jsonb(...) | z.unknown(), or the value schema you pass in — see Typed JSON columns |
q.enum(['a','b']) | text(..., { enum: [...] }) | z.enum([...]) |
q.id() | text('id').primaryKey() | z.string() |
q.scope(kind) | text(...).notNull() | z.string() |
q.stamp({ fromScope, claim }) | text(...).notNull() (nullable with optional: true) | z.string().optional() |
q.storageKey({ bucket, key, mime, maxBytes }) | text(...) | never in a request body — written by db.allocateUpload only |
.array() on q.text() / q.enum() / q.int() / q.uuid() | text(...).array() etc. | z.array(<element>) |
The Drizzle column is the Postgres form; on SQLite/D1 the compiler lowers it. The next section has the per-dialect storage for the exact-numeric, date, and array types.
In request bodies a column that is not .required() is .optional().nullable() — omit it to leave it untouched, send null to clear it. "" is not a blank: it is validated like any other value. .required() columns never accept null.
q.text() accepts either a SQL-name string or an options object — q.text({ sqlName: 'org_id', maxLength: 80 }). The options are the field-level rules:
| Option | Validation edge | Notes |
|---|---|---|
minLength: n | z.string().min(n) | "" then fails like any other short value |
maxLength: n | z.string().max(n) | The SQL column stays text (D1 ignores VARCHAR(n) length anyway) |
pattern: /re/ | z.string().regex(/re/) | Must be a regex literal, not a string or variable, so the compiler can emit it |
email: true | z.string().email() |
Every rule is enforced on the generated create, update, and batch routes, described in OpenAPI, and read by the CMS form from the schema registry. A misspelled option (maxlength) is a compile error, not a silent no-op. q.url() takes sqlName and maxLength only.
q.secret() is a write-only credential column — an API client secret, a webhook URL with an embedded token. It takes sqlName, minLength, maxLength, and pattern; it is encrypted at rest like .encrypted(), redacted on every read path for every role (owner included), and read server-side only through ctx.unmask(row, column). The table needs a q.scope('organization') column; it may be a tenant table. See Secret columns.
q.url() is q.text() plus an absolute-http(s)-URL check at the validation edge, so javascript: / data: / ftp: URIs and free-form strings are rejected before they ever land in storage or get rendered in the CMS.
q.id() emits a plain text primary key. Actual ID assignment at insert time is driven by the provider's generateId setting (default "uuid"). This keeps q's output decoupled from any specific ID library.
Typed JSON columns
Pass q.json() a Zod schema to give the column's value a shape. A table file may import { z } from zod for this:
import { feature, q } from "@quickback/compiler";
import { z } from "zod";
export default feature("journalEntries", {
columns: {
id: q.id(),
organizationId: q.scope("organization"),
autocatResult: q.json(z.object({ method: z.string(), confidence: z.number().min(0).max(1) })).optional(),
applications: q.json(z.array(z.object({ invoiceId: z.string(), amount: z.string() }))).optional(),
raw: q.json().optional(),
...q.audit(),
...q.softDelete(),
},
read: { access: { roles: ["member"] } },
create: { access: { roles: ["admin"] } },
});The schema validates create and update bodies (and changeset ops), and its JSON Schema types the column in openapi.json, api-types.gen.ts, quickback.gen.ts and the MCP tools. A bare q.json() stays unknown there. Storage doesn't change: the column is jsonb on Postgres and JSON text on SQLite/D1.
The schema must be written inline from z and literals, because the compiler copies it into the generated routes and converts it to JSON Schema itself. These are compile errors:
- a reference to another binding:
q.json(Shape), orz.object({ a: Shape }) - a callback such as
.refine(...)or.transform(...) - using
zanywhere else in the table file - importing anything from
zodother than{ z }
Indexed JSON projections (SQLite)
Use projections in the second argument of q.json(schema, options) to index a stored scalar inside a typed JSON value. It is supported on cloudflare-d1, including organization databases in SQLite Durable Objects. The alias is a query name: it does not add a physical column, a response property, or a field clients can write.
import { feature, q } from "@quickback/compiler";
import { z } from "zod";
export default feature("companies", {
columns: {
id: q.id(),
organizationId: q.scope("organization"),
metadata: q.json(z.object({
company: z.object({ industry: z.string().nullable() }).optional(),
score: z.number().optional(),
}), {
projections: {
industry: {
path: ["company", "industry"],
filterable: "in",
sortable: true,
index: { prefix: ["organizationId"] },
},
score: { path: ["score"], filterable: "range", sortable: true },
},
}).optional(),
...q.audit(),
...q.softDelete(),
},
guards: { createable: ["metadata"], updatable: ["metadata"] },
read: { access: { roles: ["member"] } },
create: { access: { roles: ["member"] } },
update: { access: { roles: ["member"] } },
});The same column options work in q.table() with defineTable(). The compiler infers string, number or boolean from the inline Zod schema. Optional and nullable properties are supported. filterable: "eq" enables equality and .ne; "in" adds .in; numeric "range" adds .gt, .gte, .lt and .lte. Declare at least one of filterable or sortable: true. A view can narrow these capabilities with query.filterable and query.sortable.
Paths must be nonempty literal arrays of property names made of ASCII letters, digits and underscores, beginning with a letter or underscore. Arrays, wildcards, objects, arbitrary SQL/JSONPath, dynamic options and ambiguous unions are rejected. Aliases begin with a letter, use the same alphabet, and must be unique across the table's JSON columns; physical column names, SQL column names, pagination controls and JavaScript prototype names are reserved. Table, source and prefix SQL identifiers use that safe property-name alphabet too. sqlName is supported within that restriction.
A projection cannot read an effectively masked, encrypted, sealed or write-only column, even if some roles can reveal that column. A keys entry with derivedFrom is also unavailable: it is computed after the SQL read. Stored organizer and platform keys can be indexed; their write authority is unchanged.
index.prefix names distinct physical scalar columns, in index order. It cannot name another projection or a JSON, array, encrypted or secret column. Each alias owns one non-unique expression index; no id suffix is added automatically. Sorting requires a non-null unique physical id column and uses the existing id tie-breaker in the query. Index names are bounded and derived from the SQL table, SQL source column and alias. Path/type/prefix edits replace that index; alias edits drop the old identity and create the new one. Existing rows need no application backfill, but building an index scans the table and consumes storage. Validate large tenant upgrades against your runtime budget before release.
Missing paths, JSON null, malformed legacy JSON, wrong scalar types, arrays/objects and non-finite numbers index as SQL NULL. No scalar coercion occurs. In particular a string "2" does not match a numeric projection. SQL comparison semantics apply: .ne does not select NULLs. See JSON projection queries for pagination and API restrictions.
Per-key write authority (keys)
createable and updatable decide whether a client may write a column. One JSON column can mix keys a project member may change with keys only a platform operator may change (entitlements, plan features, feature flags). The second argument of q.json(schema, opts) can declare a tier for each key:
import { feature, q } from "@quickback/compiler";
import { z } from "zod";
export default feature("projects", {
columns: {
id: q.id(),
name: q.text().required(),
settings: q.json(
z.object({
theme: z.string().optional(),
beta: z.boolean().optional(),
}),
{
keys: {
theme: { tier: "organizer" }, // ordinary: writable wherever `settings` is
beta: { tier: "platform" }, // generic writes refuse it
},
},
).optional(),
organizationId: q.scope("organization"),
...q.audit(),
...q.softDelete(),
},
guards: { createable: ["name", "settings"], updatable: ["name", "settings"] },
read: { access: { roles: ["member"] } },
create: { access: { roles: ["member"] } },
update: { access: { roles: ["member"] } },
});| Option | Meaning |
|---|---|
sqlName | SQL column name. The legacy positional form q.json(schema, "col") still works. |
projections.<alias> | Indexed scalar query alias; see Indexed JSON projections. |
keys.<key>.tier | "organizer" (the default): an ordinary key. "platform": see below. |
keys.<key>.derivedFrom | The key is computed from another table and never stored. Requires tier: "platform" and a z.boolean() property. |
keys needs an inline z.object({ ... }) value schema, and every key it lists must be a property of that schema. A key the schema doesn't declare, an unknown option, or a non-literal options object is a compile error.
Platform keys. Generic CRUD writes (POST, PATCH, PUT, the batch routes, and changeset ops) refuse a body that carries a platform key with 422 JSON_KEY_RESTRICTED, and details.fields names it as <column>.<key>. A PATCH that replaces the column keeps the stored platform keys: PATCH { settings: { theme: "dark" } } leaves beta as it was. Platform keys are readOnly in the column's JSON Schema (OpenAPI, api-types.gen.ts, MCP).
Only an action can change a platform key, and only one of these actions:
- an action whose
accessnames auserRolelane, when the caller'suser.rolematched it (access: { userRole: ["operator"] }); - an action that names the key in
writes:.
The scoped db enforces this rule, and so do handles from unsafeDb.scopeTo(...). Any other action that writes the column gets 422 JSON_KEY_RESTRICTED if it changes or drops a platform key. Read-modify-write that carries the key over unchanged, such as .set({ settings: { ...record.settings, theme } }), is allowed. An insert may not set a platform key without the grant. An upsert's onConflictDoUpdate({ set }) that touches the column is refused unless the action holds every grant, because the compiler cannot compare it against the stored row. The raw unsafeDb handle bypasses this check, as it bypasses the firewall.
Derived keys. derivedFrom: { table, column, in, match? } turns a key into a projection of another table. The key is true when a row of table that is linked to this row has column in the in set, and false otherwise. Soft-deleted rows don't count.
settings: q.json(
z.object({ premiumExport: z.boolean().optional() }),
{
keys: {
premiumExport: {
tier: "platform",
// true while a `plans` row for this project is active or trialing
derivedFrom: { table: "plans", column: "status", in: ["active", "trialing"] },
},
},
},
),tableis the other table's SQL name or export name, andcolumnis a column of it.match: { source, target }links the rows:sourceis a column on this table,targeta column ontable. Omit it whentablehas exactly one.references()to this table. The compiler then infers the link (plans.projectId → projects.id). Zero or several references with nomatchis a compile error.- A derived key is never stored and never writable. Every write path refuses it, actions with a grant included. CRUD reads (GET, list, views) and CRUD write responses fill it in from the source table. Realtime frames carry the stored value, which never holds a derived key. An action's
requires:also reads the source table, so the purchase or subscription row is the only source of truth.
Under generateId: "cuid", "nanoid", or "short", the q.id() default
calls an npm helper (createId from @paralleldrive/cuid2, or nanoid /
customAlphabet from nanoid). Don't import it in the table file, which may
not import either package. The compiler adds the import to the generated
schema.ts and the package to package.json, so the default mints the same
id shape as the CRUD route.
Decimals, dates, 64-bit integers, and arrays
Each of these has native Postgres DDL. SQLite has no equivalent type, so on D1 the compiler lowers it to a storage class that keeps the value exact, and the wire format is the same on both dialects:
| Builder | Postgres | SQLite / D1 | Wire value | Rejected with 400 |
|---|---|---|---|---|
q.decimal({ precision: 12, scale: 2 }) | numeric(12, 2) | TEXT | string, "1234.50" | more than precision − scale integer digits or scale fraction digits, JSON numbers, exponents |
q.date() | date | TEXT (YYYY-MM-DD) | string, "2026-03-31" | impossible dates (2026-02-30), any time or zone part |
q.bigint() | bigint | INTEGER | number | non-integers, anything outside ±(2^53 − 1) |
q.smallint() | smallint | INTEGER | number | anything outside −32768..32767 |
q.text().array(), q.enum([...]).array(), q.int().array(), q.uuid().array() | text[], text[], integer[], uuid[] | TEXT holding JSON | JSON array | non-arrays, and any element the scalar would reject (q.enum(["a"]).array() refuses ["b"]) |
import { feature, q } from "@quickback/compiler";
export default feature("invoices", {
columns: {
id: q.id(),
number: q.text({ maxLength: 40 }).required(),
total: q.decimal({ precision: 12, scale: 2 }).required().filterable("eq"),
taxRate: q.decimal({ precision: 6, scale: 5 }).optional(),
issuedOn: q.date().required().filterable("range"),
amountCents: q.bigint().required(),
lineCount: q.smallint().default(1).required(),
labels: q.text().array().default([]).required(),
channels: q.enum(["web", "phone", "store"]).array().optional(),
organizationId: q.scope("organization"),
...q.audit(),
},
read: { access: { roles: ["owner", "admin", "member"] } },
create: { access: { roles: ["owner", "admin"] } },
update: { access: { roles: ["owner", "admin"] } },
delete: { access: { roles: ["owner", "admin"] }, mode: "hard" },
});- Decimals are strings, so no value passes through a float. Send
"19.9"and the API stores and returns"19.90": the value is padded toscaledigits and leading zeros are dropped, which is how Postgres printsnumeric(p,s). D1 stores that same canonical text, so both dialects return identical strings.precision(1–1000) andscale(0–precision) must be number literals, or the compile fails. - Dates have no time zone. A
q.date()value is never converted, so"2026-03-31"is the same day for every caller. Useq.timestamp()for an instant. - Timestamps are ISO strings on the wire, on both dialects. On D1,
q.timestamp()istextholding the ISO string. On Postgres it istimestamptz. The column accepts aDateor an ISO string on write, and its TypeScript type isDate | string. Reads come back as aDate, which serializes as the same ISOZstring. Because Drizzle uses one type for reads and writes, a read is also typedDate | stringeven though it is always aDateat runtime — wrap it asnew Date(row.dueAt)before callingDatemethods such as.getTime()(a breaking type change for Postgres projects written against the earlierDate-only type). So.set({ archivedAt: now })works and typechecks on either database, on every handle: the scopeddb,unsafeDb, and a rawcreateDb(). Postgres feature schemas import this column'stimestampfrom the generatedsrc/lib/pg-timestamp.tsinstead ofdrizzle-orm/pg-core. Its SQL type and migrations are unchanged. Filter values for a Postgres timestamp column must parse as a timestamp, or the request returns400. q.bigint()values are JSON numbers, and are capped at ±(2^53 − 1). Past that, a JSON number can't hold an exact integer, and D1 returns everyINTEGERas a JS number. The cap still takes a cents column past $90 trillion, whereq.int()(Postgresinteger) stops at about $21.4 million. Values written to a Postgresbigintoutside the API beyond 2^53 will read back rounded.- Defaults are checked at compile time against the same rules, because nothing re-validates a DDL default.
q.smallint().default(40000)fails the compile. A decimal default must already be in canonical form, so write.default("0.00")for scale 2, not"0". .array()works onq.text(),q.enum(),q.int(), andq.uuid(), and must be written once..default([])gives Postgres'{}'and D1'[]'. An array column can't declare.references(): Postgres has no foreign keys over array elements, so use a join table.
What you can query depends on the type. The compiler refuses the rest at compile time, and the list endpoint refuses them at runtime too:
| Type | ?search= | .filterable() | ?sort= |
|---|---|---|---|
q.decimal on Postgres | no | eq, in, range | yes |
q.decimal on D1 | no | eq, in (the filter value is canonicalized, so ?total=19.9 matches "19.90") | no. It is TEXT there, so both sorting and range filters would compare strings. |
q.date | no | eq, in, range | yes (YYYY-MM-DD sorts correctly on both dialects) |
q.bigint, q.smallint | no | eq, in, range | yes |
.array() | no | no | no |
Every filterable column that is nullable (.optional()) also accepts ?field.isNull=true|false, whatever its type or family. See Filtering on NULL.
.searchable() and .filterable("like") are text-only. Masks that format strings (email, phone, partial, and the rest) are refused on q.bigint(), q.smallint(), and array columns; use redact or custom there. Decimal and date values are strings, so every mask type works on them. .defaultNow() is only accepted on q.timestamp().
.defaultNow() stamps the insert time whenever an insert omits the column. On Postgres it is a real DEFAULT now(). On SQLite / D1 the column carries a constant DEFAULT '1970-01-01T00:00:00.000Z' (D1 refuses a non-constant default on ALTER TABLE ADD COLUMN) plus a $defaultFn, and the generated src/db/index.ts makes every Drizzle insert use the $defaultFn — so only raw SQL that omits the column gets the epoch. Compilers from v0.33.2 until this fix wrote the epoch for Drizzle inserts too; see Troubleshooting → timestamps read 1970-01-01 to find and repair affected rows.
Naming Convention
By default, q picks the SQL column name from the JS key using the target database's conventional casing. Both cloudflare-d1 and neon default to snake_case (organizationId → organization_id).
You can override for any project by setting namingConvention on the database provider config:
// quickback/quickback.config.ts
export default {
providers: {
database: {
name: 'cloudflare-d1',
config: {
namingConvention: 'camelCase', // keep JS-style names in the SQL
},
},
},
};On Postgres with Better Auth, namingConvention: 'camelCase' fails the compile. Better Auth then camel-cases its own tables and columns (userId, organizationId), and the generated RLS policies on those tables name them in snake_case. Keep snake_case, or set compiler.securityContracts.skipManagedTables: true and ship your own RLS for the Better Auth tables.
For one-off overrides on a specific column, pass an explicit name as the positional argument:
organizationId: q.scope('organization', { sqlName: 'org_id' }), // SQL name: 'org_id'Database Schema
Define each feature with one feature() call — schema and security configuration together in a single TypeScript file.
Managed Columns
Audit fields, soft-delete fields, q.scope tenant columns, q.stamp identity columns and q.storageKey — columns the compiler populates from verified context.