VibORM

Exports Reference

Complete reference of all VibORM export paths and their contents

Exports Reference

VibORM uses multiple entry points to enable tree-shaking. Import only what you need to minimize bundle size.

Quick Overview

Entry PointSizeDescription
viborm~1 KBMain entry - client creation, errors, utilities
viborm/schema~33 KBSchema builder and native types
viborm/pg~2 KBPostgreSQL driver (node-postgres)
viborm/postgres~2 KBPostgreSQL driver (postgres.js)
viborm/pglite~1 KBPGlite driver
viborm/mysql2~2 KBMySQL driver
viborm/sqlite3~1 KBSQLite driver (better-sqlite3)
viborm/cache~0.3 KBCache types and utilities
viborm/cache/memory~0.7 KBIn-memory cache driver
viborm/validation~1 KBValidation library
viborm/instrumentation~1 KBOpenTelemetry integration
viborm/migrations~7 KBMigration utilities

viborm

Main entry point for creating clients and handling errors.

import { createClient, validateSchema, getSchemas } from "viborm";

Functions

ExportDescription
createClientCreates a VibORM client instance with the provided configuration
validateSchemaValidates a schema and returns validation results with errors/warnings
validateSchemaOrThrowValidates a schema and throws on validation errors
getSchemasCreates a proxy to access model query schemas (e.g., getSchemas(schema).user.where)
isPendingOperationType guard to check if a value is a PendingOperation
isVibORMErrorType guard to check if an error is a VibORMError
isRetryableErrorChecks if an error is retryable (transient database errors)
wrapErrorWraps an unknown error into a VibORMError

Classes

ExportDescription
PendingOperationRepresents a deferred database operation (used in transactions)
VibORMErrorBase error class for all VibORM errors
ConnectionErrorError connecting to the database
QueryErrorError executing a query
ValidationErrorSchema or input validation error
TransactionErrorTransaction-related error
UniqueConstraintErrorUnique constraint violation
ForeignKeyErrorForeign key constraint violation
NotFoundErrorRecord not found (for findUniqueOrThrow, etc.)
NestedWriteErrorError in nested create/update operations
FeatureNotSupportedErrorFeature not supported by the current driver

Enums & Constants

ExportDescription
VibORMErrorCodeEnum of all error codes

Types

ExportDescription
VibORMClientType of the client returned by createClient
VibORMConfigConfiguration options for createClient
ValidationResultResult of schema validation
SchemaValidationErrorIndividual validation error
ValidationRuleSchema validation rule definition
SeverityValidation severity ("error" or "warning")
QueryMetadataMetadata about executed queries
RawQueryResultRaw result from database driver
ResultParserParser for transforming raw results
UnwrapPendingOperationUtility type to unwrap PendingOperation<T> to T
UnwrapPendingOperationsUtility type to unwrap array of pending operations

viborm/schema

Schema definition using the s builder.

import { s, PG, MYSQL, SQLITE } from "viborm/schema";

Schema Builder

ExportDescription
sSchema builder object with all field and model methods

The s object provides:

// Fields
s.string()      // String field
s.int()         // Integer field
s.float()       // Float field
s.boolean()     // Boolean field
s.datetime()    // DateTime field
s.json()        // JSON field
s.bigint()      // BigInt field
s.bytes()       // Binary/Blob field
s.enum()        // Enum field
s.vector()      // Vector field (for embeddings)

// Relations
s.oneToOne()    // One-to-one relation
s.oneToMany()   // One-to-many relation
s.manyToMany()  // Many-to-many relation

// Model
s.model()       // Define a model

Native Types

ExportDescription
PGPostgreSQL native type mappings
MYSQLMySQL native type mappings
SQLITESQLite native type mappings

Example usage:

const user = s.model({
  id: s.string().id().ulid(),
  balance: s.float().native(PG.DoublePrecision, MYSQL.Double),
  metadata: s.json().native(PG.Jsonb),
});

Utility Functions

ExportDescription
hydrateSchemaNamesHydrates SQL names for all models and fields in a schema
isSchemaHydratedChecks if a schema has been hydrated
getModelSqlNameGets the SQL table name for a model
getFieldSqlNameGets the SQL column name for a field

Types

ExportDescription
ModelModel type
ModelStateInternal model state
AnyModelAny model type
FieldField type
NumberFieldNumber field type
AnyRelationAny relation type
GetterLazy getter function type
ReferentialActionReferential action (Cascade, SetNull, etc.)
RelationTypeRelation type (oneToOne, oneToMany, manyToMany)
NativeTypeNative type definition

viborm/driver

Base driver classes and error types for building custom drivers.

import { Driver, TransactionBoundDriver } from "viborm/driver";

Classes

ExportDescription
DriverAbstract base class for database drivers
TransactionBoundDriverDriver bound to a specific transaction
ConnectionErrorError connecting to the database
QueryErrorError executing a query
TransactionErrorTransaction-related error
UniqueConstraintErrorUnique constraint violation
ForeignKeyErrorForeign key constraint violation
FeatureNotSupportedErrorFeature not supported by the driver

Functions

ExportDescription
isRetryableErrorChecks if an error is retryable

Types

ExportDescription
AnyDriverAny driver type
DriverResultParserParser for driver results
QueryExecutionContextContext for query execution
DialectDatabase dialect (postgres, mysql, sqlite)
IsolationLevelTransaction isolation level
LogFunctionLogging function type
QueryResultQuery result type
TransactionOptionsTransaction options

viborm/pg

PostgreSQL driver using node-postgres.

import { PgDriver, createClient } from "viborm/pg";
ExportDescription
PgDriverPostgreSQL driver class
createClientCreates a client with PostgreSQL driver pre-configured
import { createClient } from "viborm/pg";
import { s } from "viborm/schema";

const client = createClient({
  schema: { user },
  options: {
    host: "localhost",
    database: "mydb",
  },
});

viborm/postgres

PostgreSQL driver using postgres.js.

import { PostgresDriver, createClient } from "viborm/postgres";
ExportDescription
PostgresDriverpostgres.js driver class
createClientCreates a client with postgres.js driver pre-configured

viborm/pglite

PGlite driver for embedded PostgreSQL.

import { PgliteDriver, createClient } from "viborm/pglite";
ExportDescription
PgliteDriverPGlite driver class
createClientCreates a client with PGlite driver pre-configured

viborm/neon-http

Neon serverless PostgreSQL driver over HTTP.

import { NeonHttpDriver, createClient } from "viborm/neon-http";
ExportDescription
NeonHttpDriverNeon HTTP driver class
createClientCreates a client with Neon HTTP driver pre-configured

viborm/bun-sql

Bun's built-in PostgreSQL driver.

import { BunSqlDriver, createClient } from "viborm/bun-sql";
ExportDescription
BunSqlDriverBun SQL driver class
createClientCreates a client with Bun SQL driver pre-configured

viborm/mysql2

MySQL driver using mysql2.

import { Mysql2Driver, createClient } from "viborm/mysql2";
ExportDescription
Mysql2DriverMySQL2 driver class
createClientCreates a client with MySQL2 driver pre-configured

viborm/planetscale

PlanetScale serverless MySQL driver.

import { PlanetscaleDriver, createClient } from "viborm/planetscale";
ExportDescription
PlanetscaleDriverPlanetScale driver class
createClientCreates a client with PlanetScale driver pre-configured

viborm/sqlite3

SQLite driver using better-sqlite3.

import { SQLite3Driver, createClient } from "viborm/sqlite3";
ExportDescription
SQLite3DriverSQLite3 driver class
createClientCreates a client with SQLite3 driver pre-configured

viborm/libsql

LibSQL/Turso driver.

import { LibsqlDriver, createClient } from "viborm/libsql";
ExportDescription
LibsqlDriverLibSQL driver class
createClientCreates a client with LibSQL driver pre-configured

viborm/bun-sqlite

Bun's built-in SQLite driver.

import { BunSqliteDriver, createClient } from "viborm/bun-sqlite";
ExportDescription
BunSqliteDriverBun SQLite driver class
createClientCreates a client with Bun SQLite driver pre-configured

viborm/d1

Cloudflare D1 driver (binding).

import { D1Driver, createClient } from "viborm/d1";
ExportDescription
D1DriverD1 driver class
createClientCreates a client with D1 driver pre-configured

viborm/d1-http

Cloudflare D1 driver over HTTP API.

import { D1HttpDriver, createClient } from "viborm/d1-http";
ExportDescription
D1HttpDriverD1 HTTP driver class
createClientCreates a client with D1 HTTP driver pre-configured

viborm/cache

Cache types and utilities.

import { CacheDriver, generateCacheKey } from "viborm/cache";

Classes

ExportDescription
CacheDriverAbstract base class for cache drivers

Functions

ExportDescription
generateCacheKeyGenerates a cache key from operation parameters
generateCachePrefixGenerates a cache key prefix for a model
parseTTLParses TTL string (e.g., "1h", "30m") to milliseconds

Constants

ExportDescription
CACHE_PREFIXDefault cache key prefix
DEFAULT_CACHE_TTLDefault TTL in milliseconds

Schemas

ExportDescription
cacheInvalidationSchemaValidation schema for cache invalidation options
withCacheSchemaValidation schema for cache options

Types

ExportDescription
AnyCacheDriverAny cache driver type
CacheEntryCache entry with value and metadata
CacheExecutionOptionsOptions for cache operations
CacheSetOptionsOptions for setting cache values
CacheInvalidationOptionsOptions for cache invalidation
CacheInvalidationSchemaSchema type for invalidation
WithCacheOptionsOptions for cached queries
WithCacheSchemaSchema type for cache options

viborm/cache/memory

In-memory cache driver.

import { MemoryCache } from "viborm/cache/memory";
ExportDescription
MemoryCacheIn-memory cache implementation with TTL support
import { MemoryCache } from "viborm/cache/memory";

const cache = new MemoryCache();
const client = createClient({
  schema: { user },
  driver: new PgDriver({ ... }),
  cache,
});

viborm/cache/cloudflare-kv

Cloudflare KV cache driver.

import { CloudflareKVCache } from "viborm/cache/cloudflare-kv";
ExportDescription
CloudflareKVCacheCloudflare KV cache implementation

viborm/client

Advanced client types for TypeScript.

import type { Client, Schema } from "viborm/client";

Classes

ExportDescription
PendingOperationRepresents a deferred database operation

Functions

ExportDescription
isPendingOperationType guard for PendingOperation

Types

ExportDescription
ClientBase client type
CachedClientClient with caching enabled
SchemaSchema type constraint
OperationsAll model operations
CacheableOperationsOperations that support caching
MutationOperationsMutation operations
OperationPayloadInput type for an operation
OperationResultResult type for an operation
WaitUntilFnFunction type for waitUntil (Cloudflare)
InferSelectIncludeInfers result type from select/include
BatchPayloadResult of batch operations
CountResultTypeResult of count operations
AggregateResultTypeResult of aggregate operations
GroupByResultTypeResult of groupBy operations
UnwrapPendingOperationUnwraps PendingOperation<T> to T
UnwrapPendingOperationsUnwraps array of pending operations

viborm/instrumentation

OpenTelemetry integration for tracing and monitoring.

import { SPAN_OPERATION, ATTR_DB_SYSTEM } from "viborm/instrumentation";

Span Names

ExportDescription
SPAN_OPERATIONTop-level operation span
SPAN_VALIDATEInput validation span
SPAN_BUILDQuery building span
SPAN_EXECUTEQuery execution span
SPAN_PARSEResult parsing span
SPAN_TRANSACTIONTransaction span
SPAN_CONNECTConnection span
SPAN_DISCONNECTDisconnection span
SPAN_CACHE_GETCache get span
SPAN_CACHE_SETCache set span
SPAN_CACHE_DELETECache delete span
SPAN_CACHE_CLEARCache clear span
SPAN_CACHE_INVALIDATECache invalidation span

Attributes

ExportDescription
ATTR_DB_SYSTEMDatabase system (e.g., postgresql)
ATTR_DB_NAMESPACEDatabase name
ATTR_DB_COLLECTIONTable/collection name
ATTR_DB_OPERATION_NAMEOperation name (e.g., findMany)
ATTR_DB_QUERY_TEXTSQL query text
ATTR_DB_QUERY_SUMMARYQuery summary
ATTR_DB_BATCH_SIZEBatch size
ATTR_DB_ROWS_RETURNEDNumber of rows returned
ATTR_ERROR_TYPEError type
ATTR_SERVER_ADDRESSServer address
ATTR_SERVER_PORTServer port
ATTR_DB_DRIVERDriver name
ATTR_DB_QUERY_PARAMETER_PREFIXQuery parameter prefix
ATTR_CACHE_DRIVERCache driver name
ATTR_CACHE_KEYCache key
ATTR_CACHE_RESULTCache result (hit/miss)
ATTR_CACHE_TTLCache TTL

Types

ExportDescription
InstrumentationConfigFull instrumentation config
TracingConfigTracing configuration
LoggingConfigLogging configuration
LogCallbackLog callback function
LogEventLog event type
LogLevelLog level (debug, info, warn, error)
VibORMSpanNameUnion of all span names

viborm/validation

Validation library for runtime type checking.

import { v } from "viborm/validation";

Validation Builder

ExportDescription
vValidation builder object

The v object provides:

// Primitives
v.string()      // String schema
v.number()      // Number schema
v.integer()     // Integer schema
v.boolean()     // Boolean schema
v.bigint()      // BigInt schema
v.date()        // Date schema

// Complex
v.object()      // Object schema
v.array()       // Array schema
v.union()       // Union schema
v.literal()     // Literal schema
v.enum()        // Enum schema
v.nullable()    // Nullable wrapper
v.optional()    // Optional wrapper

// Utilities
v.lazy()        // Lazy evaluation (for recursive types)
v.custom()      // Custom validation

viborm/migrations

Database migration utilities.

import { createMigrationClient, push, diff } from "viborm/migrations";

Client

ExportDescription
createMigrationClientCreates a migration client
MigrationContextMigration execution context

Operations

ExportDescription
applyApplies pending migrations
pendingLists pending migrations
rollbackRolls back migrations
statusGets migration status
downRuns down migrations
pushPushes schema changes directly (dev mode)
resetResets database and re-applies migrations
squashSquashes multiple migrations into one

Generation

ExportDescription
generateGenerates a new migration file
previewPreviews migration without writing
diffComputes diff between schemas
hasDestructiveOperationsChecks for destructive changes
getDestructiveOperationDescriptionsGets descriptions of destructive changes

DDL

ExportDescription
generateDDLGenerates DDL statements from diff
introspectIntrospects current database schema
formatOperationFormats a single diff operation
formatOperationsFormats multiple diff operations

Resolvers

ExportDescription
createResolverCreates a custom resolver
createUnifiedResolverCreates a unified resolver
createPredefinedResolverCreates a resolver with predefined answers
addDropResolverResolver that adds/drops (no renames)
alwaysAddDropResolverAlways add/drop resolver
alwaysRenameResolverAlways rename resolver
lenientResolverLenient resolver (allows destructive)
strictResolverStrict resolver (rejects destructive)
rejectAllResolverRejects all ambiguous changes
applyResolutionsApplies resolutions to diff
resolveAmbiguousChangesResolves ambiguous changes interactively
formatAmbiguousChangeFormats an ambiguous change
formatAmbiguousChangesFormats multiple ambiguous changes

Serialization

ExportDescription
serializeModelsSerializes models to snapshot format
getTableNameGets SQL table name for a model
getColumnNameGets SQL column name for a field

Storage

ExportDescription
MigrationStorageDriverAbstract base for migration storage

Utilities

ExportDescription
DEFAULT_MIGRATIONS_DIRDefault migrations directory
DEFAULT_TABLE_NAMEDefault migrations table name
formatMigrationFilenameFormats migration filename
generateMigrationNameGenerates migration name
normalizeDialectNormalizes dialect string
sortOperationsSorts operations for execution order

Errors

ExportDescription
MigrationErrorMigration-specific error
isMigrationErrorType guard for MigrationError

Types

ExportDescription
DiffOperationSingle diff operation
DiffResultResult of schema diff
MigrationEntryMigration file entry
AppliedMigrationApplied migration record
SchemaSnapshotSchema snapshot
TableDefTable definition
ColumnDefColumn definition
IndexDefIndex definition
ForeignKeyDefForeign key definition
PrimaryKeyDefPrimary key definition
UniqueConstraintDefUnique constraint definition
EnumDefEnum definition
AmbiguousChangeAmbiguous change (rename vs add/drop)
ResolverResolver function type
UnifiedResolverUnified resolver type
... and more

viborm/adapters

Database adapters (advanced/internal use).

import { PostgresAdapter, MySQLAdapter, SQLiteAdapter } from "viborm/adapters";
ExportDescription
PostgresAdapterPostgreSQL SQL adapter
MySQLAdapterMySQL SQL adapter
SQLiteAdapterSQLite SQL adapter

These are used internally by drivers to generate database-specific SQL.

On this page