Skip to content
VibORM
Esc
↑↓navigate↵open⌘Jpreview
On this page

String

String scalar type for text data with auto-generation, validation, and native type options

Basic Usage

import { s } from "viborm";

s.string(); // Required string
s.string().nullable(); // string | null
s.string().array(); // string[] (native on PG, JSON on MySQL/SQLite)

Common modifiers (.nullable(), .unique(), .default(), .map(), .schema()) are covered in the modifier reference. To override the column type (varchar(n), uuid, citext, …), see Native Types; s.string({ pg: PG.STRING.CITEXT, mysql: MYSQL.STRING.LONGTEXT }) chooses one per database.

MySQL indexed strings

A bare s.string() maps to TEXT on MySQL. A primary key, unique constraint, index, or foreign key changes that bare column to the conservative VARCHAR(191) mapping: its stored value is limited to 191 characters. Adding an index later can therefore narrow an existing TEXT column; migration preview reports that type change as destructive. Review the stored data before consenting. Strict-mode admission prevents silent truncation, and an oversized value produces ValueTooLongError rather than establishing an application validation guarantee.

Choose the physical length explicitly when 191 is unsuitable:

import { s } from "viborm";
import { MYSQL } from "viborm/schema";

s.string(MYSQL.STRING.VARCHAR(512)).unique();

The provider’s index-byte limits still apply, including compound indexes and character-set width. Native VARCHAR bounds are enforced by the database; VibORM does not infer a corresponding upstream .schema() length refinement. Declare that refinement separately when early input validation is required.

IDs and Auto-Generation

.id() marks the field as the primary key and auto-generates a ULID by default:

s.string().id(); // PK, auto-generated ULID: "01ARZ3NDEKTSV4RRFFQ69G5FAV"
s.string().id("user"); // Prefixed: "user-01ARZ3NDEKTSV4RRFFQ69G5FAV"
s.string().id({ generate: false }); // Natural key: caller must supply it

Chain a generator to pick a different format:

s.string().id().uuid(); // UUIDv4: "550e8400-e29b-41d4-a716-446655440000"
s.string().id().uuidv7(); // UUIDv7: "0199c4e2-79b0-7f3a-8c21-9f2d6b4a1e08" (time-sortable)
s.string().id().ulid(); // ULID: "01ARZ3NDEKTSV4RRFFQ69G5FAV" (sortable, the default)
s.string().id().ksuid(); // KSUID: "0ujtsYcgvSTl8PAuAdqWYSMnLOv" (time-sortable)
s.string().id().nanoid(); // NanoID: "V1StGXR8_Z5jdHi6B-myT"
s.string().id().nanoid(10); // NanoID with custom length
s.string().id().cuid(); // CUID2: "ajenr87qeqg87w8vjc7xiaie"

Formats alone validate caller values; they do not install defaults. This keeps foreign keys from inventing references when omitted. Request generation on a non-key field explicitly:

s.string().uuid(); // Caller supplies a UUID
s.string().uuid({ generate: true, prefix: "token" }); // Generated default
s.string().nanoid({ length: 21, generate: true, prefix: "token" });

Requested identifiers are generated by VibORM itself — no identifier library is installed alongside it — and every value is drawn from crypto.getRandomValues. A runtime that cannot provide secure randomness is refused rather than served a weaker identifier.

Every generator accepts a prefix — .ulid("user") produces "user-01ARZ...". For .nanoid(), the prefix is the second argument: .nanoid(21, "user"). A nanoid length must be a whole number of characters between 1 and 65536 — one character costs one byte of entropy, and 65536 bytes is all crypto.getRandomValues serves in one call — refused at declaration.

.id() is a key declaration that normally carries a default: it never replaces a format already spelled, so .uuid("u").id() and .id().uuid("u") are the same field. Spelling a prefix on both (.uuid("u").id("p")) names two prefixes for one field and is refused. The opt-out also commutes with the format: .id({ generate: false }).uuid() and .uuid().id({ generate: false }) both require a caller value. An explicit .default(...) is retained when either modifier is applied.

Ordering guarantees differ by format. ULID is monotonic within a process: two values minted in the same millisecond still sort in the order they were issued. UUIDv7 and KSUID are time-sortable but make no same-millisecond promise, and UUIDv4, NanoID and CUID2 carry no time at all.

Naming a format is a promise about every value

There are two different declarations above, and the difference decides how the column is stored and which values it accepts.

.id() declares a key. It carries a ULID generator so you need not supply one, but it says nothing about the values the field will hold: they are whatever a string column holds, stored as text, exactly as before.

.uuid(), .uuidv7(), .ulid(), .ksuid(), .nanoid() and .cuid() declare a domain. Naming the format is a promise that every value of the field belongs to it, and VibORM holds you to it and takes advantage of it:

const user = s.model({ id: s.string().id().uuid("usr") });

// With a client `db` configured with schema: { user }:
db.user.findUnique({ where: { id: "usr-a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11" } }); // ok
db.user.findUnique({ where: { id: "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11" } }); // refused: the prefix is part of the value
db.user.findUnique({ where: { id: "user-42" } }); // refused: not a uuid

Admission covers every position a value can appear in: create, update, where, unique selectors, cursors, and every connect / connectOrCreate / upsert key. A prefix is matched whole — nothing splits on - — and aliases normalize once, before anything identity-sensitive sees the value: an uppercase UUID and a lowercase ULID address exactly the row their canonical spelling does.

Storage

A named format is stored as the identifier itself rather than as the text you write it as. The prefix is a fact of the declaration, identical in every row, so only the payload is stored and the prefix is re-applied on read.

Format PostgreSQL MySQL SQLite
uuid, uuidv7 uuid BINARY(16) BLOB
ulid bytea (16 bytes) BINARY(16) BLOB
ksuid bytea (20 bytes) BINARY(20) BLOB
nanoid, cuid text TEXT TEXT
.id() with no format text TEXT TEXT

A ULID is never spelled as a uuid: its bytes are not a UUID’s, and a database that formatted them as one would publish a version nibble the value does not have.

What compact storage buys. Measured on the project’s containers at 200,000 rows per table (scripts/measure-id-storage.mjs; the raw numbers are in docs/architecture/native-ids-evidence/final.json):

Compared to text Table + index Index alone
PostgreSQL uuid as uuid −37% −47%
PostgreSQL ULID as bytea −14% −18%
MySQL uuid as BINARY(16) −26% to −29% (clustered key) −46% as a secondary index
MySQL ULID as BINARY(16) −22% (clustered key) −24% as a secondary index

Random uuids gain the most because a text btree over them fragments as well as being wider; a time-sorted format saves mostly on width.

Foreign keys derive. A column that references a key holds exactly what that key holds, so it needs no declaration of its own — it is admitted, normalized and stored the same way automatically. See Relations.

What compact storage costs. contains, startsWith, endsWith and mode are removed from a compactly stored field’s filter type and refused by the engine: sixteen bytes are not the text you wrote them as, and a substring of that text is a question the column cannot answer. Everything else is intact and exact — equals, not, in, notIn, lt, lte, gt, gte, orderBy and cursor pagination — because the byte order of all four compact formats IS their canonical text order (and, for uuidv7, ulid and ksuid, their time order). nanoid and cuid stay text and keep every string operator; only their equals / in / notIn operands have to be values of the domain.

The four predicates go by the FORMAT, not by the storage: a compact format that took the text-family override below still loses them. The validation schema is built before any adapter exists, so it cannot know which dialect this field will be bound to, let alone which column that dialect chose — and one filter type per field, rather than one per deployment, is the answer that keeps the type and the runtime saying the same thing. _min and _max answer with the earliest and latest identifier, for the same reason ordering works, and _count and groupBy are unaffected.

An existing table. A column that already holds text has two routes: keep it (below) or convert the rows. Both, with the per-dialect recipes and the pre-check queries VibORM renders for them, are on Converting identifier columns.

Keeping a text column. A native type from the text family opts out of compact storage while keeping the domain validated — this is the route for a column that already holds text:

s.string(PG.STRING.VARCHAR(40)).id().uuid("usr"); // varchar(40), still admits only prefixed uuids

PostgreSQL accepts text, citext, varchar(n), bytea and — for the two uuid formats — uuid. MySQL accepts its TEXT family, BINARY(n), VARBINARY(n) and BLOB, where n must be the format’s own width. SQLite accepts TEXT and BLOB. Anything else is refused where it is declared, with a message naming the spellings that format does accept. A map with one entry per database applies this per dialect: s.string({ pg: PG.STRING.VARCHAR(40) }).id().uuid() keeps text on PostgreSQL and compact storage on MySQL and SQLite, and a foreign key to it follows each dialect’s choice.

PostgreSQL’s char(n) is not among them, though it is an ordinary string override: character(n) blank-pads to its full width, so a 36-character uuid in a char(40) column reads back with four trailing spaces and no value of the domain is ever returned. MySQL’s CHAR(n) strips that padding on the way out and stays accepted there.

Custom Validation

.schema() accepts any Standard Schema. Valibot actions like email() are not schemas on their own — wrap them in pipe():

import { email, maxLength, minLength, pipe, regex, string } from "valibot";

s.string().schema(pipe(string(), email()));
s.string().schema(pipe(string(), minLength(3), maxLength(100)));
s.string().schema(pipe(string(), regex(/^[a-z]+$/)));

Examples

import { email, pipe, string, minLength, maxLength, regex } from "valibot";

// Email with validation
const userEmail = s.string()
  .unique()
  .schema(pipe(string(), email()));

// Username with constraints
const username = s.string()
  .unique()
  .schema(pipe(string(), minLength(3), maxLength(30), regex(/^[a-z0-9_]+$/)));

// Primary key with ULID
const id = s.string().id().ulid();

// Optional bio
const bio = s.string().nullable().default(null);

// Tags array (native array on PostgreSQL)
const tags = s.string().array().default([]);

Was this page helpful?