Annotations Reference
Complete reference for all @db.* annotations available in .as files. Generic annotations are provided by @atscript/db/plugin via dbPlugin() and work with every adapter. Adapter-specific annotations (PostgreSQL, MySQL, MongoDB) require the corresponding adapter plugin.
Annotations never travel across field refs
A field that references another interface's field (an FK like authorId: User.id, or a view/dict field) inherits the target's value and presentation annotations (@meta.label, @expect.*, UI hints, literal @db.amount.currency/@db.unit tags) — but never its structural @db.* annotations. All @db.index.*, @db.column.*, @db.default.*, @db.rel.*, @db.search.*, @db.agg.*, @db.encrypted, @db.json, @db.ignore, and adapter-specific field annotations describe the storage of the table that declares them and stay there.
The same holds for the annotations that describe an entity rather than a field — @db.table and @db.table.*, @db.view and @db.view.*, @db.schema, @db.space, @db.http.path, @db.sync.method, @db.depth.limit, and the interface-level adapter annotations: a field typed with a table (customer?: Customer) and a @db.alias type carry none of them (since 0.1.141 — before, they inherited the table's db.table and each was a second runtime entity of the same table). A plain export type Admin = User is User itself at runtime (since @atscript/typescript 0.2): the same entity under a second name, not a second one. Only the interface that declares @db.table / @db.view is a DB entity; isDbEntityType is the runtime test.
The sibling-ref quantity bindings — @db.amount.currency.ref and @db.unit.ref — also stay: they name a field of the declaring interface, which the referring interface may not have. A view that mirrors a measure and its currency/unit column re-declares the one-line .ref binding on its own field.
Practically: declaring @db.index.unique on User.id never creates an index on tables that FK-ref it; if the referring table needs an index on its FK column, declare one on the FK field itself. This holds at any ref depth (including refs through an intermediate dict/view interface). extends is different — inherited props keep all their annotations, structural ones included, because the child table physically owns those columns.
Tables & Columns
| Annotation | Applies To | Arguments | Description |
|---|---|---|---|
@db.table | Interface | name? (string) | Mark as database table (defaults to interface name) |
@db.table.renamed | Interface | oldName (string) | Previous table name for schema sync migration |
@db.schema | Interface | name (string) | Assign to a database schema/namespace |
@db.space | Interface | name (string) | Assign to a named DbSpace for multi-database apps — groups the model manifest and drives token-based controller binding |
@db.depth.limit | Interface | depth (number) | Security guard on nested writes. Default 0 rejects any nested insert / replace / patch with HTTP 400. Raise N to allow deep writes up to that depth. Does not affect /meta shape. |
@db.column | Field | name (string) | Override the physical column name (perf note) |
@db.column.renamed | Field | oldName (string) | Previous column name for schema sync migration |
@db.column.collate | Field | collation (string) | Portable collation: 'binary', 'nocase', or 'unicode' |
@db.column.derived | Field | — | A string / number / boolean leaf of a @db.json field of the same table as its own read-only, indexable column (customerId: Order.payload.customer.id) — see Derived Columns (since 0.1.141) |
@db.column.precision | Field | precision (number), scale (number) | Decimal precision/scale for DB storage (e.g., DECIMAL(10,2)) |
@db.column.dimension | Field | — | Mark as dimension field — groupable in aggregate queries |
@db.column.measure | Field | — | Mark as measure field — aggregatable (sum, avg, count, min, max). Numeric/decimal only |
@db.column.filterable | Field | — | Allow this field in client-side filter clauses when the table is in @db.table.filterable 'manual' mode (see below) |
@db.column.sortable | Field | — | Allow this field in client-side sort keys when the table is in @db.table.sortable 'manual' mode (see below) |
@db.column.version | Field | — | Mark a non-optional int field as the row's OCC version. Auto-bumped on every write that changes a non-exempt column; combine with inline $cas for conflict detection. See Optimistic Concurrency |
@db.column.version.exempt | Field | — | Mark a field as version-exempt: a patch writing only exempt fields does not bump the version (and adds no version check). Nested fields are covered by an exempt object; $cas, replace and touchMany still bump (since 0.1.150). See Version-exempt fields |
@db.table.filterable | Interface | mode? ('auto' | 'manual') | Filter-gating mode. 'auto' (default) keeps all columns filterable; 'manual' requires @db.column.filterable on each filterable field |
@db.sort.nulls | Field | placement ('first' | 'last') | Default NULL placement when a query sorts by this field without a $nulls entry (since 0.1.153, see below) |
@db.table.sortable | Interface | mode? ('auto' | 'manual') | Sort-gating mode. 'auto' (default) keeps all columns sortable; 'manual' requires @db.column.sortable on each sortable field |
@db.json | Field | — | Store as a single JSON column instead of flattening |
@db.ignore | Field | — | Exclude field from the database schema entirely |
@db.column.searchable | Field | — | Include a string or integer field in the generic $search fallback (case-insensitive substring across annotated fields; an integer matches by substring of its decimal text) when the adapter has no native search; native search wins when configured. Floats, decimals and timestamps are refused |
@db.writeOnly | Field | — | HTTP write-only seal: settable via insert/update/replace, never present in read responses (projections exclude it; filter/sort/groupBy rejected; /meta flags it writeOnly so forms render set-only inputs). Pair with @db.encrypted for sealed secrets |
@db.table 'users'
@db.schema 'auth'
interface User {
@db.column 'full_name'
name: string
@db.json
preferences: Preferences
@db.ignore
computedField: string
@db.column.collate 'nocase'
username: string
@db.column.precision 10, 2
price: number
}@db.column performance
Only use @db.column when you have a genuine reason — such as mapping to a legacy schema or meeting an external naming convention you cannot change. When a table has no @db.column, nested objects, or @db.json fields, the read, filter, and patch paths take a zero-allocation fast path that skips key translation entirely. Adding even one @db.column activates per-row key remapping on every read, write, filter, and patch operation for that table. In high-throughput scenarios this overhead is measurable.
If you control the database schema, prefer naming your Atscript fields to match the desired column names directly. See Custom Column Names for more details.
Query Gate
By default, every column on a @db.table is filterable and sortable — this preserves back-compat for tables where the author hasn't thought about the query surface. When a table should expose a narrow query surface (e.g., a customer-facing reports endpoint), opt into manual mode:
@db.table 'users'
@db.table.filterable 'manual'
@db.table.sortable 'manual'
interface User {
@meta.id
id: number
@db.column.filterable
email: string
@db.column.sortable
createdAt: number.timestamp
}Semantics:
@db.table.filterable 'manual'makes the readable controller reject (HTTP 400) any filter clause that references a field without@db.column.filterable.@db.table.sortable 'manual'does the same for sort keys against@db.column.sortable.@db.table.filterable 'auto'/@db.table.sortable 'auto'are documentary no-ops — they match the default behaviour when the annotation is absent, but make the author's intent explicit.- The two gates are independent: a table can opt into strict filtering while leaving sort open, or vice versa.
- Without the annotation, behaviour is unchanged from previous releases — all columns are filterable/sortable.
The /meta endpoint exposes a per-field capability entry in fields[<path>] so clients can show or hide query controls per column. Since 0.1.128 fields and the request gate are two projections of one capability index, so what /meta advertises is exactly what the server accepts:
filterable—truewhen value comparisons (equality, ranges,$in,$regex, …) on the field are accepted: the adapter can compare the column (canFilterField) and the field is neither@db.writeOnlynor@db.encrypted; in'manual'mode additionally only for fields carrying@db.column.filterable.filterOps(since 0.1.132) — present only whenfilterableisfalsebut narrower operators still pass: the list of those operators. On SQL adapters a@db.json/ array column reports["$exists"]and adb.geoPointcolumn["$exists"], plus"$geoWithin"when the adapter is geo-searchable. Offer only these operators for the field in a filter UI. The same@db.writeOnly/@db.encrypted/'manual'rules apply, so a field blocked by one of them has nofilterOps— existence would reveal whether a sealed value is set. See Existence.sortable—truewhen the adapter can sort the column (canSortField) and the field is neither@db.writeOnlynor@db.encrypted; in'manual'mode additionally only for fields carrying@db.column.sortable. In'auto'mode every adapter-sortable column is advertised (before 0.1.128 only index-backed fields were, although$sorton the others succeeded).indexed— present (true) when the field is index-backed (explicit@db.index*, primary key, unique). Advisory only: a hint for UIs that prefer cheap sort keys; it never changes whether a$sortis accepted.bucketable(since 0.1.132) — present (true) exactly when a calendar bucket over the field is accepted — see which fields can be bucketed. The top-levelbucketUnitslists the units that adapter supports.
Adapter capability is a hard gate over the annotation policy: @db.json and array columns are never sortable on any adapter (SQL adapters accept only $exists on them; MongoDB and the memory adapter filter them natively). Nested-object parents (contact) and navigation paths (assignee, assignee.name) are never listed; on SQL adapters the descendants of a JSON column (prefs.theme) are not listed either — they are on MongoDB / memory, where dotted paths are native.
Parity is enforced (since 0.1.128)
sortable: true ⇔ $sort=<path> is accepted and filterable: true ⇔ a value-comparison filter on <path> is accepted — on every adapter, mode and field kind. When filterable is false, a filter entry is accepted only if its operators are listed in filterOps (an $exists entry must be its only operator). Everything else, and every path that is not listed, is rejected with HTTP 400 and the envelope { message, statusCode: 400, errors: [{ path, message }] } naming the reason: missing annotation, adapter storage type, @db.writeOnly, navigation path (use $with), JSON descendant (select the parent), nested object (use one of its leaves). $groupBy, $having keys and aggregate fields use the physical capability only — the 'manual' policy applies to filters and $sort.
Adapter capabilities are re-read (since 0.1.132)
Some adapter capabilities are known only after schema sync — PostgreSQL detects PostGIS during sync. The capability index behind /meta and the request gate is rebuilt when those capabilities change. Up to 0.1.131 it was fixed when the controller was constructed, so a controller created before syncSchema() kept advertising and enforcing the pre-sync answer (for example, geo search unsupported) until restart.
@db.sort.nulls
Since 0.1.153. Where null / missing values of this field go when a query sorts by it and names no $nulls entry for it: 'first' before every value, 'last' after every value, in both sort directions.
@db.table 'tickets'
interface Ticket {
@meta.id
id: number
@db.sort.nulls 'last'
closedAt?: number.timestamp // open tickets sort after closed ones, asc or desc
}- An explicit
$nullsentry (URL$sort=closedAt:first) overrides it. It also applies to the$rowOrderoffirst()/last()and to a grouped$sorton the field. - Nullable fields only. On a required top-level table field the compiler warns and the default has no effect (the field is never
null). AT | nullfield (since 0.1.155), a required leaf inside an optional object, and every view field can benulland are honoured. - An object, array,
@db.jsonor@db.encryptedfield is a compile error: it is not sortable. - The non-native placement costs the index its ORDER BY — see Index use.
/metakeeps the annotation in the serializedtype(metadata["db.sort.nulls"]) so a UI can show the placement next to the sort control. On an adapter without NULL placement support (/meta.nullsPlacementabsent) the default is ignored.
HTTP
| Annotation | Applies To | Arguments | Description |
|---|---|---|---|
@db.http.path | Interface | path (string) | HTTP endpoint path for this table. Used by UI for value-help on FK fields. Published at runtime from the controller's computed route (the canonical one when the model has several) |
@db.table 'authors'
@db.http.path '/authors'
interface Author {
@meta.id
id: number
name: string
}When a controller is registered without an explicit prefix, @db.http.path is used as the route. After app.init() the app publishes the final computed route (including parent routes) as @db.http.path, so FK references always carry the correct URL — see Several controllers over one model when a model is mounted more than once.
Normalization contract
The value carried in type.metadata["db.http.path"] has distinct semantics for writers and readers:
- Writers (annotation at compile time): the value is an optional route hint, and it stays the hint — decorators and
assertExposedread what you declared, never a path published later. The controller's computed route takes precedence at runtime, so the annotation may be omitted or overridden by the mount point. - Readers (UI / client code / custom consumers): the published value is always (a) prefixed with a leading
/, with empty segments and a trailing/removed, (b) inclusive of the MoostglobalPrefix, and (c) the final public URL — usable verbatim withfetch()ornew Client(url). In/metait is resolved for the app serving the request: references carry the model's canonical route, the root of a controller's own/metacarries that controller's own route, and an ambiguous model carries none. The model's runtime metadata mirrors the last app that published.
Example: an author writes @db.http.path '/authors'; a consumer reading type.metadata["db.http.path"] at runtime sees /api/db/tables/authors when the controller is mounted under globalPrefix: '/api' at /db/tables/authors.
Depth Limit (security guard)
@db.depth.limit N is a security guard on nested-write payloads — a declared ceiling on how deep a client can send nested inserts, replaces, or patches through @db.rel.from relations. Payloads deeper than N are rejected at the server boundary with HTTP 400 before any database access. Default when the annotation is absent is 0, meaning no nested writes are accepted at all; authors opt in explicitly to N >= 1 when they want the server to accept deep writes.
This annotation affects only write acceptance. It does not change /meta serialization, read/query behaviour, or wire shape (see the separate note below).
@db.table 'authors'
@db.depth.limit 2
interface Author {
@meta.id
id: number
name: string
@db.rel.from
posts?: Post[]
}BREAKING CHANGE
Tables without @db.depth.limit are now treated as @db.depth.limit 0: the server rejects any nested-write payload (HTTP 400) before reaching the database. Previously the server accepted arbitrary-depth nested writes via the implicit nested-writer. That implicit behaviour has been removed: tables that require nested writes must opt in explicitly with @db.depth.limit N for the appropriate N.
/meta FK ref shape is independent
/meta always ships FK fields as shallow refs ({ id, metadata }) regardless of @db.depth.limit. The target's db.http.path is carried in the ref metadata, so clients can resolve value-help URLs and fetch the target's own /meta on demand when they need deeper structure. Nav-prop trees (@db.rel.from / @db.rel.to / @db.rel.via) are fully expanded in meta regardless of this annotation, so the write-payload shape clients need is unaffected. (Prior releases shipped refDepth: 1 and coupled meta expansion to @db.depth.limit; that coupling has been removed.)
Defaults
| Annotation | Applies To | Arguments | Description |
|---|---|---|---|
@db.default | Field | value (string, number or boolean) | Static default value — a literal of the field's type; a string on a non-string field is parsed as JSON |
@db.default.increment | Field | start? (number) | Auto-incrementing integer (requires number type) |
@db.default.uuid | Field | — | Random UUID string (requires string type) |
@db.default.now | Field | — | Current timestamp (requires number or string type) |
@db.onUpdate.now | Field | — | Set to the current time by every update (requires number type) — see Update Timestamps |
@db.onUpdate.inc | Field | — | Change counter: 0 on insert, +1 on every update (non-optional top-level integer; since 0.1.162) — see Change Counter |
@db.table
interface Product {
@meta.id
@db.default.uuid
id: string
@db.default 'untitled'
name: string
@db.default.now
createdAt: number
@db.default.now
@db.onUpdate.now
updatedAt: number // or: updatedAt: number.timestamp.updated
}Indexes
| Annotation | Applies To | Arguments | Description |
|---|---|---|---|
@db.index.plain | Field | name? (string), sort? (string) | Standard index, optional sort direction ('asc'/'desc') |
@db.index.unique | Field | name? (string) | Unique constraint index |
@db.index.fulltext | Field | name? (string), weight? (number) | Full-text search index with optional weight; an index-backed integer member matches by exact number |
Use the same index name on multiple fields to create a composite index.
@db.table
interface Article {
@db.index.unique
slug: string
@db.index.plain 'date_idx', 'desc'
publishedAt: number
// Composite index across two fields
@db.index.plain 'author_cat'
authorId: string
@db.index.plain 'author_cat'
category: string
@db.index.fulltext 'search', 3
title: string
@db.index.fulltext 'search', 1
body: string
}Search
| Annotation | Applies To | Arguments | Description |
|---|---|---|---|
@db.search.vector | Field | dimensions (number), similarity? (string), indexName? (string) | Vector search field |
@db.search.vector.threshold | Field | value (number) | Default minimum $score (0--1) |
@db.search.filter | Field | indexName (string) | Pre-filter field for vector search |
Similarity options: 'cosine' (default), 'euclidean', 'dotProduct'. Each adapter maps to its native vector type — see Text Search and Vector Search.
dimensions is any positive integer that matches your embedding model output — see Vector Search.
@db.table
interface Document {
@db.search.vector 1536, 'cosine', 'doc_vec'
@db.search.vector.threshold 0.7
embedding: db.vector
@db.search.filter 'doc_vec'
category: string
}Relations
| Annotation | Applies To | Arguments | Description |
|---|---|---|---|
@db.rel.FK | Field | alias? (string) | Foreign key (field must use chain ref). Dual role — see note below |
@db.rel.to | Field | alias? (string) | Forward navigation (N:1, FK on this table) |
@db.rel.from | Field | alias? (string) | Reverse navigation (1:N, FK on other table) |
@db.rel.via | Field | junction (ref) | Many-to-many navigation through a junction table |
@db.rel.onDelete | Field | action (string) | Referential action on parent delete |
@db.rel.onUpdate | Field | action (string) | Referential action on parent update |
@db.rel.filter | Field | condition (expr) | Static filter on a navigation property — applied in $with and in $some / $none (since 0.1.147; ignored before) |
@db.rel.filterable | Field | — | Lets HTTP clients filter parents by this relation with $some / $none (details, since 0.1.147). Nav fields only; not part of the schema hash |
@db.table
interface Task {
@meta.id
id: number
status: 'open' | 'done'
@db.rel.FK
@db.rel.onDelete 'cascade'
projectId: Project.id
@db.rel.FK 'parent'
parentId?: Task.id
@db.rel.to
project: Project
@db.rel.from
comments: Comment[]
@db.rel.via TaskTag
@db.rel.filterable
tags: Tag[]
@db.rel.from 'parent'
@db.rel.filter `status = 'open'`
openSubtasks: Task[]
}@db.rel.FK dual role
@db.rel.FK serves two purposes depending on the host interface:
- On a
@db.tableinterface it drives DB-relation semantics — the relation loader pairs it with@db.rel.to/@db.rel.from, it participates in@db.rel.viajunction resolution, and the integrity layer validates it at write time. - On any other interface (value-help dictionaries, WF forms, plain interfaces) it acts purely as the value-help indicator: the client-side picker resolver reads
@db.rel.FKto decide which fields render a value-help picker, and the URL for the picker comes from the target's@db.http.path.
The host-restriction rule was relaxed so the same annotation covers both cases — authors don't need a separate marker for value-help. All other validation rules still apply (the target must be a chain reference to a @meta.id or @db.index.unique field).
Since 0.1.128 the marker also travels through reference chains in /meta and /meta/form/:name: a field declared as code: Issue.code, where Issue.code: Dict.code carries @db.rel.FK, is serialized with ref pointing at the terminal field (Dict.code, shallow { id, metadata } at the unchanged refDepth: 0.5) and db.rel.FK: true — so value-help pickers on view fields target the dictionary, not the intermediate table. Only the serialized meta changes; the runtime type and the database constraints are untouched.
Referential Action Values
For @db.rel.onDelete and @db.rel.onUpdate:
| Action | Description |
|---|---|
'cascade' | Propagate delete/update to related rows |
'restrict' | Prevent operation if related rows exist |
'noAction' | Database default behavior (no action) |
'setNull' | Set FK to null (field must be optional) |
'setDefault' | Set FK to default value (needs @db.default) |
Views
| Annotation | Applies To | Arguments | Description |
|---|---|---|---|
@db.view | Interface | name? (string) | Mark as database view (defaults to interface name) |
@db.view.for | Interface | entry (ref) | Entry table — or view — of a managed view |
@db.view.joins | Interface | target (ref), condition (expr), kind? ('inner' | 'left'), order? (order) | Explicit join (repeatable, applied in order; kinds & chains); an order makes it a first-row join (since 0.1.147) |
@db.alias | Type | target (ref) | Join alias of a table or view |
@db.view.filter | Interface | condition (expr) | View WHERE clause |
@db.view.having | Interface | condition (expr) | Post-aggregation HAVING clause |
@db.view.materialized | Interface | — | Mark the view as materialized |
@db.view.renamed | Interface | oldName (string) | Previous view name for schema sync migration |
@db.view
@db.view.for Task
@db.view.joins Project, `Project.id = Task.projectId`
@db.view.filter `Task.status = 'active'`
interface ActiveTaskView {
taskName: Task.name
projectName: Project.name
dueDate: Task.dueDate
}Aggregation
| Annotation | Applies To | Arguments | Description |
|---|---|---|---|
@db.agg.sum | Field | field (string), condition? (query) | SUM of a source column (numeric/decimal only) |
@db.agg.avg | Field | field (string), condition? (query) | AVG of a source column (numeric/decimal only) |
@db.agg.count | Field | field? (string), condition? (query) | COUNT — omit the field (or pass '*') for COUNT(*), provide a field name for non-null count |
@db.agg.countDistinct | Field | field (string), condition? (query) | COUNT(DISTINCT field) — distinct non-null values |
@db.agg.min | Field | field (string), condition? (query) | MIN of a source column |
@db.agg.max | Field | field (string), condition? (query) | MAX of a source column |
@db.compute | Field | expression (expr) | Computed column: arithmetic over the view's own fields (since 0.1.147) |
The optional condition makes the aggregate conditional: it reads only the rows the query matches, e.g. @db.agg.sum 'amount', `status = 'paid'` .
Use aggregation annotations on view fields. The view's plain (non-aggregated) fields become its GROUP BY columns automatically — they need no @db.column.dimension, which only makes runtime $groupBy queries strict.
@db.view
@db.view.for Order
@db.view.having `totalRevenue > 100`
interface CategoryStats {
category: Order.category
@db.agg.sum 'amount'
totalRevenue: number
@db.agg.count
orderCount: number
@db.agg.avg 'amount'
avgOrderValue: number
}Quantity Tagging (currency & unit)
Bind a numeric field to its dimension (currency code, unit of measure) so the runtime can enforce correct aggregation grouping and the readable controller can guarantee the dimension is always shipped alongside the value.
| Annotation | Applies To | Arguments | Description |
|---|---|---|---|
@db.amount.currency | Field (decimal) | code (string) | Hard-coded ISO-style currency code ('EUR', 'USD', 'BTC'). Validated against ^[A-Z0-9]{2,10}$. Schema-wide constant — no runtime aggregation constraint. UI reads it from /meta. |
@db.amount.currency.ref | Field (decimal) | fieldName (string) | Bind this amount to a sibling field that holds the per-row currency code. Sibling must exist and resolve to a string (preferably db.currencyCode). |
@db.unit | Field (decimal|number) | code (string) | Hard-coded unit of measure ('kg', 'rpm', 'qps', 'requests/sec'). Free-form string — no shape validation. Schema-wide constant. |
@db.unit.ref | Field (decimal|number) | fieldName (string) | Bind this quantity to a sibling field holding the per-row unit. Sibling must exist and resolve to a string. |
The two forms (literal vs .ref) are mutually exclusive on the same field. Money-bearing fields must be decimal — floats lose cents. Quantity fields accept both decimal (weights, lengths) and number (counts, rates).
db.currencyCode primitive
Companion type for the .ref target — a string constrained to ^[A-Z0-9]{2,10}$ so non-currency strings can't be silently used as the dimension.
@db.table 'orders'
interface Order {
@meta.id
@db.default.uuid
id: string
// Per-row currency: each line carries its own code.
currency: db.currencyCode
@db.amount.currency.ref 'currency'
@db.column.measure
amount: decimal
}
@db.table 'metrics'
interface Metric {
@meta.id
@db.default.uuid
id: string
// Single-currency table: literal form, no sibling field.
@db.amount.currency 'EUR'
@db.column.measure
fee: decimal
// Mixed-unit measurement: ref form.
unit: string
@db.unit.ref 'unit'
@db.column.measure
weight: decimal
// Single-unit metric: literal form.
@db.unit 'qps'
@db.column.measure
rate: number
}Runtime behavior
- Aggregation guard. When
aggregate()is called against a field carrying@db.amount.currency.refor@db.unit.ref, the referenced field MUST appear in$groupBy. OtherwiseDbError("INVALID_QUERY"). Literal forms (@db.amount.currency 'EUR',@db.unit 'kg') impose no runtime constraint — the dimension is satisfied schema-wide.COUNT(*)is exempt. $selectauto-widening. Themoost-dbreadable controller automatically adds the referenced sibling to$selectwhenever its tagged value is requested. UI can ask for$select=amountand still receivecurrencyin the response. Literal forms are NOT widened — the constant is on the field descriptor, not row data.- Field descriptors.
TDbFieldMetaexposescurrencyCode/currencyRefField/unitCode/unitRefFieldso clients can format quantities correctly without inspecting raw annotations.
Schema Sync
| Annotation | Applies To | Arguments | Description |
|---|---|---|---|
@db.sync.method | Interface | method (string) | Sync strategy: 'drop' or 'recreate' |
'drop'— Drop and recreate the table on structural changes (lossy, data is deleted).'recreate'— Recreate with data preservation on structural changes.
Patch Behavior
| Annotation | Applies To | Arguments | Description |
|---|---|---|---|
@db.patch.strategy | Field | strategy (string) | 'replace' (default) or 'merge' |
Controls how nested objects are handled during PATCH/update operations. With 'replace', the entire nested object is overwritten. With 'merge', individual sub-fields are deep-merged.
PostgreSQL-Specific
These annotations require the @atscript/db-postgres plugin. See PostgreSQL adapter.
| Annotation | Applies To | Arguments | Description |
|---|---|---|---|
@db.pg.type | Field | type (string) | Override native PG column type (e.g., CITEXT, INET, MACADDR) |
@db.pg.schema | Interface | schema (string) | PostgreSQL schema (default: public) |
@db.pg.collate | Interface / Field | collation (string) | Native PG collation (overrides portable @db.column.collate) |
// requires the @atscript/db-postgres plugin in atscript.config
@db.table 'users'
@db.pg.schema 'auth'
interface User {
@meta.id
@db.default.uuid
id: string
@db.pg.type 'CITEXT'
email: string
@db.pg.collate 'tr-x-icu'
name: string
}MySQL-Specific
These annotations require the @atscript/db-mysql plugin. See MySQL adapter.
| Annotation | Applies To | Arguments | Description |
|---|---|---|---|
@db.mysql.engine | Interface | engine (string) | Storage engine (default: InnoDB); any engine the server has |
@db.mysql.charset | Interface / Field | charset (string) | Character set (default: utf8mb4); any set the server has |
@db.mysql.collate | Interface / Field | collation (string) | Native MySQL collation (overrides portable @db.column.collate) |
@db.mysql.unsigned | Field | — | UNSIGNED modifier for integer columns |
@db.mysql.type | Field | type (string) | Override native MySQL column type (e.g., MEDIUMTEXT, TINYTEXT) |
@db.mysql.onUpdate | Field | expression (string) | ON UPDATE: CURRENT_TIMESTAMP or CURRENT_TIMESTAMP(n) |
// requires the @atscript/db-mysql plugin in atscript.config
@db.table 'events'
@db.mysql.engine 'InnoDB'
@db.mysql.charset 'utf8mb4'
interface Event {
@meta.id
@db.default.increment
id: number
@db.mysql.type 'MEDIUMTEXT'
description: string
@db.mysql.unsigned
viewCount: number
@db.default.now
@db.mysql.onUpdate 'CURRENT_TIMESTAMP'
updatedAt: number
}MongoDB-Specific
These annotations require the @atscript/db-mongo plugin. See MongoDB adapter.
| Annotation | Applies To | Arguments | Description |
|---|---|---|---|
@db.mongo.collection | Interface | — | Mark as MongoDB collection (auto-injects _id) |
@db.mongo.capped | Interface | size (number), max? (number) | Capped collection with max byte size and optional doc limit |
@db.mongo.search.dynamic | Interface | analyzer? (string), fuzzy? (number) | Dynamic Atlas Search index |
@db.mongo.search.static | Interface | analyzer? (string), fuzzy? (number), indexName? (string), strategy? (string) | Named static Atlas Search index. strategy: compound (default) / autocomplete / text |
@db.mongo.search.text | Field | analyzer? (string), indexName? (string) | Include field in a search index (word match) |
@db.mongo.search.autocomplete | Field | indexName? (string), tokenization? (string), minGrams? (number), maxGrams? (number), foldDiacritics? (boolean), analyzer? (string) | Prefix/typeahead field (double-mapped as string). tokenization: edgeGram (prefix, default) / nGram (substring) / rightEdgeGram (suffix) |
When indexName is omitted it defaults to "DEFAULT" — interface-level and field-level annotations referencing the same name are merged into one Atlas Search index. See MongoDB adapter — Atlas Search.
// requires the @atscript/db-mongo plugin in atscript.config
@db.table 'products'
@db.mongo.collection
@db.mongo.search.static 'lucene.english', 1, 'main_search'
interface Product {
@meta.id
_id: mongo.objectId
@db.mongo.search.text 'lucene.english', 'main_search'
name: string
@db.search.vector 1536, 'cosine', 'vec_idx'
embedding: number[]
@db.search.filter 'vec_idx'
category: string
}Generic search annotations
@db.search.vector and @db.search.filter are generic annotations (not MongoDB-specific) and work across all adapters that support vector search. See the Search section above.
Editor support
In the Atscript VSCode extension (with @atscript/core 0.1.94 or later) the arguments that name fields and types get completion, hover, go-to-definition, find-references and rename. Each argument's editor scope is the one its diagnostics check:
| Argument | Scope |
|---|---|
@db.view.filter condition | The entry table and every join (@db.alias names included); an unqualified field belongs to the entry |
@db.view.joins condition | The join target, the entry table and the joins declared before it (chained joins) |
@db.view.having condition | The view's own fields, unqualified |
@db.view.joins ordering (4th argument) | The join target's fields |
@db.compute expression | The view's own fields, unqualified |
@db.agg.* condition | The same scope as the view's @db.view.filter |
@db.agg.* field ('amount', 'settings.level') | A field path of the entry table (of the field's chain-ref type when it has one), completed level by level |
@db.rel.filter condition | The related type, plus the junction table of a @db.rel.via |
@db.view.for, @db.alias target | Completes @db.table and @db.view types |
@db.view.joins target | Completes tables, views and @db.alias types |
@db.rel.via junction | Completes @db.table types |
Related Annotations
These are not @db.* annotations but are commonly used alongside the database layer.
| Annotation | Applies To | Arguments | Description |
|---|---|---|---|
@meta.id | Field | — | Mark as primary key field (multiple fields form a composite key) |
@expect.array.key | Field | — | Array element key field for patch matching |
@expect.array.uniqueItems | Field | — | Enforce unique items in an array |
@db.table
interface OrderLine {
// Composite primary key
@meta.id
orderId: Order.id
@meta.id
productId: Product.id
quantity: number
}