Skip to content
🚀 This documentation is for unreal-orm 1.0.0 alpha which requires SurrealDB 2.0 alpha SDK. For the stable version, see npm.

Unreal

const Unreal: object

Defined in: unreal.ts:65

The Unreal namespace provides a unified API for:

  • Configuration: Database connection setup
  • Schema: DDL generation and application
  • AST: Schema parsing, comparison, and migration

applySchema: (db, definables, method) => Promise<void>

Apply schema definitions to the database. Creates/updates tables, fields, and indexes.

Generates and applies the full SurrealQL schema to a SurrealDB instance.

Surreal

The SurrealDB instance to apply the schema to.

Definable[]

An array of Definable entities (model classes and index definitions).

The method to use for schema application if a table already exists.

"IF NOT EXISTS" | "OVERWRITE" | "error"

Promise<void>

await Unreal.applySchema(db, [User, Post, idx_user_email]);

readonly ast: object

AST utilities for schema parsing, comparison, and migration.

readonly areEqual: (source, target) => boolean = schemasAreEqual

Check if two schemas are equal.

Checks if two schemas are identical (no changes).

SchemaAST

First schema

SchemaAST

Second schema

boolean

true if schemas are semantically identical

readonly compare: (source, target, isPush) => SchemaChange[] = compareSchemas

Compare two schemas and return the differences.

Compares two SchemaAST objects and returns structured changes. This enables semantic diffing instead of string comparison.

SchemaAST

The “source of truth” schema (what we want to apply)

SchemaAST

The “target” schema (what currently exists)

boolean = false

If true, source=code, target=database (pushing code to DB) If false, source=database, target=code (pulling DB to code)

SchemaChange[]

Array of schema changes

const codeSchema = extractSchemaFromDefinables([User, Post]);
const dbSchema = await introspectDatabase(db);
// Find what needs to change in DB to match code
const changes = compareSchemas(codeSchema, dbSchema, true);
// Find what needs to change in code to match DB
const changes = compareSchemas(dbSchema, codeSchema, false);

readonly extractIndex: (indexDef) => object = extractIndexFromDefinition

Extract IndexAST from an index definition.

Extracts an IndexAST from a runtime index definition.

IndexDefinition

The index definition to extract from

object

Object containing the IndexAST and associated table name

index: IndexAST

tableName: string

const { index, tableName } = extractIndexFromDefinition(emailIndex);
// { index: { name: "email_idx", columns: ["email"], unique: true }, tableName: "user" }

readonly extractSchema: (definables) => SchemaAST = extractSchemaFromDefinables

Extract SchemaAST from model classes and index definitions.

Extracts a complete SchemaAST from an array of definables (models and indexes).

Definable[]

Array of model classes and index definitions

SchemaAST

Complete SchemaAST

import { User, Post, emailIndex } from "./tables";
const schema = extractSchemaFromDefinables([User, Post, emailIndex]);
// { tables: [{ name: "user", ... }, { name: "post", ... }] }

readonly extractTable: (modelClass) => TableAST = extractTableFromModel

Extract TableAST from a model class.

Extracts a TableAST from a runtime model class.

AnyModelClass

The model class to extract from

TableAST

Complete TableAST (indexes populated separately)

const tableAST = extractTableFromModel(User);
// { name: "user", type: "NORMAL", fields: [...], ... }

extractTableName: (ql) => string | undefined

Extract table name from a DEFINE TABLE statement.

Extracts the table name from a DEFINE FIELD or DEFINE INDEX statement.

string

The raw SurrealQL statement

string | undefined

The table name or undefined

readonly filterByType: (changes, types) => SchemaChange[] = filterChangesByType

Filter changes by type (added, removed, modified).

Filters changes to only include specific types.

SchemaChange[]

Array of schema changes

ChangeType[]

Change types to include

SchemaChange[]

Filtered array of changes

readonly generateMigration: (changes, schema?) => string = generateMigrationSurql

Generate migration SurrealQL from schema changes.

Generates only the DEFINE/REMOVE statements needed for specific changes. This is used for generating migrations from schema diffs.

SchemaChange[]

Array of schema changes from compareSchemas

SchemaAST

Optional source schema for full table definitions

string

SurrealQL migration statements

const changes = compareSchemas(codeSchema, dbSchema, true);
const migration = generateMigrationSurql(changes, codeSchema);
await db.query(migration);

readonly generateSurql: (schema, method) => string = generateSurqlFromAST

Generate SurrealQL from SchemaAST.

Generates a complete SurrealQL schema from SchemaAST.

SchemaAST

The schema AST

SchemaApplicationMethod = "error"

Schema application method

string

Complete SurrealQL schema as a string

const schema = extractSchemaFromDefinables([User, Post]);
const sql = generateSurqlFromAST(schema, "OVERWRITE");
await db.query(sql);

readonly groupByTable: (changes) => Map<string, SchemaChange[]> = groupChangesByTable

Group schema changes by table name.

Groups schema changes by table for easier processing.

SchemaChange[]

Array of schema changes

Map<string, SchemaChange[]>

Map of table name to changes for that table

isIndexDefinition: (value) => value is IndexDefinition

Check if a value is an index definition.

Type guard to check if a value is an index definition.

unknown

value is IndexDefinition

isModelClass: (value) => value is AnyModelClass

Check if a value is a model class.

Type guard to check if a value is a model class.

unknown

value is AnyModelClass

readonly parseField: (ql) => FieldAST = parseFieldDefinition

Parse a DEFINE FIELD statement into AST.

Parses a DEFINE FIELD statement into a FieldAST.

string

The raw SurrealQL DEFINE FIELD statement

FieldAST

Complete FieldAST

const field = parseFieldDefinition("DEFINE FIELD email ON TABLE user TYPE string");
// { name: "email", type: "string", flex: false, ... }

readonly parseIndex: (ql) => IndexAST = parseIndexDefinition

Parse a DEFINE INDEX statement into AST.

Parses a DEFINE INDEX statement into an IndexAST.

string

The raw SurrealQL DEFINE INDEX statement

IndexAST

Complete IndexAST

const index = parseIndexDefinition("DEFINE INDEX email_idx ON TABLE user FIELDS email UNIQUE");
// { name: "email_idx", columns: ["email"], unique: true }

readonly parseTable: (ql) => Partial<TableAST> = parseTableDefinition

Parse a DEFINE TABLE statement into AST.

Parses a DEFINE TABLE statement into a partial TableAST.

string

The raw SurrealQL DEFINE TABLE statement

Partial<TableAST>

Partial TableAST (fields, indexes, events are populated separately)

const table = parseTableDefinition("DEFINE TABLE user SCHEMAFULL");
// { name: "user", type: "NORMAL", schemafull: true, ... }

clearConfig: () => void

Clear the global database configuration. Useful for testing or switching connections.

Clears the global database configuration. Useful for testing or when switching connections.

void

configure: (options) => void

Configure the global database connection. After calling this, ORM methods can be used without passing db explicitly.

Configures the global database connection for the ORM.

After calling configure(), you can use ORM methods without passing db:

// Before: always pass db
const users = await User.select(db, { limit: 10 });
// After: db is optional
const users = await User.select({ limit: 10 });

ConfigureOptions

Configuration options

void

// Option 1: Pass a pre-connected database
const db = new Surreal();
await db.connect("ws://localhost:8000");
configure({ database: db });
// Option 2: Use a factory function (lazy initialization)
configure({
getDatabase: async () => {
const db = new Surreal();
await db.connect(process.env.SURREAL_URL);
return db;
}
});
// With factory function (recommended)
Unreal.configure({ getDatabase: () => connectToDatabase() });
// With pre-connected instance
Unreal.configure({ database: db });

readonly generateSchema: (definables, method) => string = generateFullSchemaQl

Generate full SurrealQL schema from definitions.

Generates the full SurrealQL schema for all provided definable entities (tables and indexes).

Definable[]

An array of Definable entities (model classes and index definitions).

The method to use for schema application if a table already exists.

"IF NOT EXISTS" | "OVERWRITE" | "error"

string

A string containing the complete SurrealQL schema.

const ddl = Unreal.generateSchema([User, Post]);
console.log(ddl);
// DEFINE TABLE user SCHEMAFULL;
// DEFINE FIELD email ON user TYPE string;
// ...

getDatabase: () => Promise<SurrealLike>

Get the configured database instance.

Gets the configured database instance. If a factory was provided, it will be called and the result cached.

Promise<SurrealLike>

The database instance

Error if no database is configured

// In a custom model method
class User extends Table.normal(...) {
async customMethod() {
const db = await getDatabase();
return db.query(surql`SELECT * FROM user WHERE active = true`);
}
}

Error if no database is configured

hasDatabase: () => boolean

Check if a database is configured.

Checks if a database is configured (either directly or via factory).

boolean

true if a database is configured