Defaults & Generated Values
Atscript lets you set default values directly in your .as schema. Defaults ensure fields are populated automatically on insert — you define them once, and every adapter handles the rest. A last-modified time that every update sets is covered under Update Timestamps.
Static Defaults
Use @db.default to assign a fixed value when a field is not provided at insert time. Write the value as a literal of the field's type — a string, a number or true / false:
@db.default 'pending'
status: string
@db.default false
isArchived: boolean
@db.default 0
retryCount: number
@db.default 9.99
price: decimalA number or a boolean must fit the field's type: @db.default true on a number field is a compile error. A string is accepted on any field: on a string field it is the value, on any other field it is parsed as JSON — the only way to write an object or array default, and the form older schemas use for numbers and booleans:
@db.default '0' // same as @db.default 0
retryCount: number
@db.default '[]'
tags: string[]A literal and its canonical string spelling are the same value and give the same column default — 0 and '0', -1.5 and '-1.5', true and 'true' — so switching between them does not change the schema hash. Other spellings of a number are the same value but not the same text: 1.50 is stored as 1.5 and 1e3 as 1000, so moving from '1.50' to 1.50 changes the column default's text (and the hash). Write an integer beyond 2⁵³ as a string: a number literal loses its precision. A decimal default is filled as its text (9.99 → "9.99"), like any decimal value.
A field's @normalize.* applies to its default too: with @normalize.lowercase, @db.default 'NEW' is stored as "new" — by an insert through the table, in the column's DEFAULT (a row written outside the SDK gets it too), and in the value MongoDB fills existing documents with when the field is added. A literal the normalizers leave as it is keeps its spelling, so the schema hash does not change.
@db.default 'NEW'
@normalize.lowercase
status: string // DEFAULT 'new'Literal defaults — 0.1.170
@db.default 0 and @db.default true work since 0.1.170; earlier versions take a string only (@db.default '0').
Generated Defaults
Some defaults need to be computed at insert time. Atscript provides three portable generated-default annotations:
@db.default.increment — Auto-Incrementing Integer
Generates sequential integers (1, 2, 3, ...). The field must be a number type. An optional argument sets the starting value:
@db.default.increment
id: number
// With optional start value:
@db.default.increment 1000
id: number@db.default.uuid — Random UUID
Generates a random UUID v4 string. The field must be a string type:
@db.default.uuid
id: string@db.default.now — Current Timestamp
Captures the current time at insert. Works with number (Unix epoch milliseconds) and string (ISO format) types:
@db.default.now
createdAt?: numberUse number (epoch ms) for timestamps so they cross HTTP boundaries without any serialization step.
Semantic types
number.timestamp.created already includes @db.default.now, and number.timestamp.updated includes @db.default.now and @db.onUpdate.now — you don't need to add them:
// Concise — the types carry the annotations
createdAt: number.timestamp.created
updatedAt: number.timestamp.updated
// Equivalent verbose form
@db.default.now
createdAt: number.timestamp
@db.default.now
@db.onUpdate.now
updatedAt: number.timestampThe annotations apply wherever the field's type is number.timestamp.created / number.timestamp.updated: directly, through a type alias (type Created = number.timestamp.created), as number.timestamp.created | null, and on a field of an embedded object. They do not apply to a field that references another field (createdAt: Order.createdAt copies the type, not the default), to a member of another union (number.timestamp.created | string), to a tuple item or to an array element. An explicit @db.default on the field wins (for an updated field it replaces the insert value only; updates still set the time).
A top-level number.timestamp.created is insert-only (since 0.1.165): a replace keeps the stored value and no replace or patch payload can change it — see Replace One.
Before 0.1.155 (atscript 0.1.104) the default was not applied to number.timestamp.created fields, and before 0.1.156 (atscript 0.1.106) number.timestamp.updated was neither filled nor set — see Upgrading for the schema change it brings.
Update Timestamps
@db.onUpdate.now sets a number field to the current time (epoch milliseconds) on every update. Pair it with @db.default.now to fill it on insert too — number.timestamp.updated is that pair:
updatedAt: number.timestamp.updated
// last edit only — required on insert, then set by every update
@db.onUpdate.now
editedAt?: number.timestamp- Which writes set it — patches (
updateOne,bulkUpdate,updateMany), replaces (replaceOne,bulkReplace,replaceMany) and touches (a versioned touch,touchMany— since 0.1.162), including nested relation writes on the related table's own fields,PATCH/PUTthrough moost-db and@atscript/db-client. Inserts (also withonConflict: 'ignore') are left to the field's default. - The SDK writes the time — one time per call, in the write's own statement, the same on SQLite, PostgreSQL, MySQL, MongoDB and the in-memory adapter:
updateManystamps every matched row with it. No engine trigger orON UPDATEclause is created, so writes made outside atscript-db (raw SQL, other clients) leave the field unchanged. On MySQL you can add@db.mysql.onUpdate "CURRENT_TIMESTAMP"for those as well. - A value in the payload is overridden — on a patch or a replace the caller cannot set the field (an HTTP client cannot forge it). On insert an explicit value wins, as for every default; strip it in an
onWritehook if clients must not choose it. - Write guards see the time in a replace's rows; a patch's rows do not carry the row's own update fields — the time is added after the guard, when the patch is known to write something.
- A write that changes nothing stays a no-op — a patch with no other field than the row's key (or the row's own timestamp fields) runs no statement and keeps the stored time. A versioned touch (key +
$casonly) andtouchManydo write the row, so they set it (before 0.1.162 they bumped the version only). - Nested fields —
audit.updatedAtis set when the write carriesaudit: a replace always does, a patch only when it includes the object. In an array of objects every item is set, and every item an array patch adds or updates ($insert,$upsert,$replace,$update). An array without@expect.array.keymatches$upsertand unique$insertitems by their whole value, which then includes the new time, so such an item is always added — give the array a key. Below a tuple or a union of several object types the field is not set: the payload's value is stored and required. - Version-exempt patches — the time is set but does not count as a write for
@db.column.version.exempt: a patch that writes only exempt fields still keeps the version. - Validation — the field may be omitted on replace (server and db-client), and on insert when it also has a default.
/metakeeps the annotation so forms can show the field as server-managed. - MySQL — with
@db.default.nowthe column is aTIMESTAMP: the time is stored in whole seconds unless the field declares@db.mysql.type "TIMESTAMP(3)"(see Fractional seconds).
@db.onUpdate.now requires a number field and cannot be combined with @meta.id, @db.column.version, @db.onUpdate.inc, @db.encrypted or @db.column.derived.
Change Counter
@db.onUpdate.inc (since 0.1.162) is a per-row change counter: 0 on insert, then +1 in the same statement on every SDK update of the row. Use it as a "did this row change" token for polling and sync — unlike an update time it never collides within a millisecond and never moves backwards when a clock steps:
@db.onUpdate.inc
rev: number.int- Which writes move it — every write that
@db.onUpdate.nowsets (above), by exactly one per write: patches (including patches that write only version-exempt fields), replaces, a versioned touch,touchMany, boundedupdateMany, HTTPPATCH/PUT. The engine adds one to the stored value (rev = rev + 1, MongoDB$inc/$add), so concurrent writes never lose an increment. - Inserts — the value is
0unless the insert supplies one (an import can carry existing counters). Schema sync creates the columnNOT NULL DEFAULT 0, so adding the annotation to a populated table backfills0. - A value in the payload is ignored on a patch or a replace — clients cannot set it over HTTP. An empty patch writes nothing and leaves it unchanged.
- No compare-and-set, no effect on versioning — it is not a
@db.column.version:$casdoes not target it, and it neither makes nor breaks a version-exempt patch. - Not covered — raw SQL and native foreign-key actions (
ON DELETE SET NULLrun by the engine). Application-level set-null actions (MongoDB, memory) go throughupdateManyand do move it. - Validation and
/meta— the field may be omitted on insert and replace (server and db-client);/metakeeps the annotation so forms can treat the field as server-managed. - Per row, not per table — it answers "did this row change since I read it", not "what changed since cursor X" across rows.
@db.onUpdate.inc requires a non-optional integer field (number.int, or @expect.int) at the top level of the table, and cannot be combined with @meta.id, @db.column.version, @db.onUpdate.now, @db.default*, @db.json, @db.encrypted or @db.column.derived.
Version Defaults
The @db.column.version annotation implies a 0 default — you don't need to add @db.default 0 (and you shouldn't try to write the column directly anyway; see Direct-write rejection):
@db.column.version
version: number.int
// Inserted rows get version = 0 automatically.
// SQL adapters emit DDL with NOT NULL DEFAULT 0 — ALTER TABLE backfills
// existing rows when the column is added later.
// Mongo writers inject version: 0 at insert when the field is missing.Every successful write thereafter increments the column by 1, server-side. See Optimistic Concurrency (Row Versioning) for the full feature.
How Defaults Interact with Inserts
Understanding when defaults apply:
- Omitted fields — the default value is used. This is the primary use case.
undefinedvalues ≡ omitted (since 0.1.128) — a key whose value isundefinedis dropped before defaults and validation run, at every nesting depth, so{ cap: undefined }gets the default exactly like leavingcapout. Before 0.1.128 SQL adapters bound it asNULL(a constraint error onNOT NULLcolumns).nullremains an explicit NULL.- Explicit values — if you pass a value for a field with a default, your value takes precedence. The default is only a fallback.
- Static defaults are filled SDK-side on every adapter (since 0.1.128) —
@db.default 'x'is written explicitly into the row before validation, also on SQL adapters whose DDL carries the sameDEFAULTclause (writing the column's own default is equivalent to leaving it out). Rows therefore reach validators and write guards complete. Function defaults (@db.default.now/.uuid/.increment) stay adapter-native: they are generated SDK-side only when the adapter does not handle them in the engine (see each adapter's page). - Optional fields without defaults — become
NULLif omitted from the insert. - Fields with
@db.default.increment— typically omitted from inserts entirely. The database generates the next value. - Fields of embedded objects (since 0.1.155) — a default on
audit.atis set insideauditwhen the row has anauditobject; an absent ornullembedded object stays absent: on PostgreSQL and MySQL, whereaudit.atis a column with the default in its DDL, an insert or replace withoutauditwritesNULLinto the object's columns, so the engine default does not make it appear. In an array of objects every item gets it, and inside a@db.jsonvalue (which has no column default) the SDK fillsnow/uuidon every adapter. Below a tuple or a union of several object types ([A, B],(A | B)[]) the item a default belongs to is not known, so it is not filled, and the field is required on insert like a field without a default — by the server, by@atscript/db-clientand by a form that validates against/metawith@atscript/db/validator. - Defaulted fields pass validation when omitted — insert and replace validation (server and db-client) accept a row without a field that has a
@db.default*, even when it is not optional (except below a tuple or a union of several types, see above). The TypeScript type still requires it unless it has?(next item). - Non-optional fields without defaults — must always be provided.
@db.defaultdoes not make a field optional in TypeScript — you still need?if you want to omit it from inserts.
// Only 'title' is required — all other fields are optional (marked with ?)
await todos.insertOne({ title: "Learn Atscript" });
// Result:
// {
// id: 1, ← @db.default.increment
// title: 'Learn Atscript',
// completed: false, ← @db.default false (field is optional with ?)
// description: null, ← optional, no default
// createdAt: 1710500000000 ← @db.default.now
// }Next Steps
- Indexes & Constraints — database indexes, precision, and collation
- Tables & Fields — declaring tables, primary keys, and field types
- CRUD Operations — insert, query, update, and delete data