Unreal
constUnreal: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
Type Declaration
Section titled “Type Declaration”applySchema()
Section titled “applySchema()”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.
Parameters
Section titled “Parameters”Surreal
The SurrealDB instance to apply the schema to.
definables
Section titled “definables”Definable[]
An array of Definable entities (model classes and index definitions).
method
Section titled “method”The method to use for schema application if a table already exists.
"IF NOT EXISTS" | "OVERWRITE" | "error"
Returns
Section titled “Returns”Promise<void>
Example
Section titled “Example”await Unreal.applySchema(db, [User, Post, idx_user_email]);
readonlyast:object
AST utilities for schema parsing, comparison, and migration.
ast.areEqual()
Section titled “ast.areEqual()”
readonlyareEqual: (source,target) =>boolean=schemasAreEqual
Check if two schemas are equal.
Checks if two schemas are identical (no changes).
Parameters
Section titled “Parameters”source
Section titled “source”First schema
target
Section titled “target”Second schema
Returns
Section titled “Returns”boolean
true if schemas are semantically identical
ast.compare()
Section titled “ast.compare()”
readonlycompare: (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.
Parameters
Section titled “Parameters”source
Section titled “source”The “source of truth” schema (what we want to apply)
target
Section titled “target”The “target” schema (what currently exists)
isPush
Section titled “isPush”boolean = false
If true, source=code, target=database (pushing code to DB) If false, source=database, target=code (pulling DB to code)
Returns
Section titled “Returns”Array of schema changes
Example
Section titled “Example”const codeSchema = extractSchemaFromDefinables([User, Post]);const dbSchema = await introspectDatabase(db);
// Find what needs to change in DB to match codeconst changes = compareSchemas(codeSchema, dbSchema, true);
// Find what needs to change in code to match DBconst changes = compareSchemas(dbSchema, codeSchema, false);ast.extractIndex()
Section titled “ast.extractIndex()”
readonlyextractIndex: (indexDef) =>object=extractIndexFromDefinition
Extract IndexAST from an index definition.
Extracts an IndexAST from a runtime index definition.
Parameters
Section titled “Parameters”indexDef
Section titled “indexDef”IndexDefinition
The index definition to extract from
Returns
Section titled “Returns”object
Object containing the IndexAST and associated table name
index:
IndexAST
tableName
Section titled “tableName”tableName:
string
Example
Section titled “Example”const { index, tableName } = extractIndexFromDefinition(emailIndex);// { index: { name: "email_idx", columns: ["email"], unique: true }, tableName: "user" }ast.extractSchema()
Section titled “ast.extractSchema()”
readonlyextractSchema: (definables) =>SchemaAST=extractSchemaFromDefinables
Extract SchemaAST from model classes and index definitions.
Extracts a complete SchemaAST from an array of definables (models and indexes).
Parameters
Section titled “Parameters”definables
Section titled “definables”Definable[]
Array of model classes and index definitions
Returns
Section titled “Returns”Complete SchemaAST
Example
Section titled “Example”import { User, Post, emailIndex } from "./tables";
const schema = extractSchemaFromDefinables([User, Post, emailIndex]);// { tables: [{ name: "user", ... }, { name: "post", ... }] }ast.extractTable()
Section titled “ast.extractTable()”
readonlyextractTable: (modelClass) =>TableAST=extractTableFromModel
Extract TableAST from a model class.
Extracts a TableAST from a runtime model class.
Parameters
Section titled “Parameters”modelClass
Section titled “modelClass”The model class to extract from
Returns
Section titled “Returns”Complete TableAST (indexes populated separately)
Example
Section titled “Example”const tableAST = extractTableFromModel(User);// { name: "user", type: "NORMAL", fields: [...], ... }ast.extractTableName()
Section titled “ast.extractTableName()”extractTableName: (
ql) =>string|undefined
Extract table name from a DEFINE TABLE statement.
Extracts the table name from a DEFINE FIELD or DEFINE INDEX statement.
Parameters
Section titled “Parameters”string
The raw SurrealQL statement
Returns
Section titled “Returns”string | undefined
The table name or undefined
ast.filterByType()
Section titled “ast.filterByType()”
readonlyfilterByType: (changes,types) =>SchemaChange[] =filterChangesByType
Filter changes by type (added, removed, modified).
Filters changes to only include specific types.
Parameters
Section titled “Parameters”changes
Section titled “changes”Array of schema changes
Change types to include
Returns
Section titled “Returns”Filtered array of changes
ast.generateMigration()
Section titled “ast.generateMigration()”
readonlygenerateMigration: (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.
Parameters
Section titled “Parameters”changes
Section titled “changes”Array of schema changes from compareSchemas
schema?
Section titled “schema?”Optional source schema for full table definitions
Returns
Section titled “Returns”string
SurrealQL migration statements
Example
Section titled “Example”const changes = compareSchemas(codeSchema, dbSchema, true);const migration = generateMigrationSurql(changes, codeSchema);await db.query(migration);ast.generateSurql()
Section titled “ast.generateSurql()”
readonlygenerateSurql: (schema,method) =>string=generateSurqlFromAST
Generate SurrealQL from SchemaAST.
Generates a complete SurrealQL schema from SchemaAST.
Parameters
Section titled “Parameters”schema
Section titled “schema”The schema AST
method
Section titled “method”SchemaApplicationMethod = "error"
Schema application method
Returns
Section titled “Returns”string
Complete SurrealQL schema as a string
Example
Section titled “Example”const schema = extractSchemaFromDefinables([User, Post]);const sql = generateSurqlFromAST(schema, "OVERWRITE");await db.query(sql);ast.groupByTable()
Section titled “ast.groupByTable()”
readonlygroupByTable: (changes) =>Map<string,SchemaChange[]> =groupChangesByTable
Group schema changes by table name.
Groups schema changes by table for easier processing.
Parameters
Section titled “Parameters”changes
Section titled “changes”Array of schema changes
Returns
Section titled “Returns”Map<string, SchemaChange[]>
Map of table name to changes for that table
ast.isIndexDefinition()
Section titled “ast.isIndexDefinition()”isIndexDefinition: (
value) =>value is IndexDefinition
Check if a value is an index definition.
Type guard to check if a value is an index definition.
Parameters
Section titled “Parameters”unknown
Returns
Section titled “Returns”value is IndexDefinition
ast.isModelClass()
Section titled “ast.isModelClass()”isModelClass: (
value) =>value is AnyModelClass
Check if a value is a model class.
Type guard to check if a value is a model class.
Parameters
Section titled “Parameters”unknown
Returns
Section titled “Returns”value is AnyModelClass
ast.parseField()
Section titled “ast.parseField()”
readonlyparseField: (ql) =>FieldAST=parseFieldDefinition
Parse a DEFINE FIELD statement into AST.
Parses a DEFINE FIELD statement into a FieldAST.
Parameters
Section titled “Parameters”string
The raw SurrealQL DEFINE FIELD statement
Returns
Section titled “Returns”Complete FieldAST
Example
Section titled “Example”const field = parseFieldDefinition("DEFINE FIELD email ON TABLE user TYPE string");// { name: "email", type: "string", flex: false, ... }ast.parseIndex()
Section titled “ast.parseIndex()”
readonlyparseIndex: (ql) =>IndexAST=parseIndexDefinition
Parse a DEFINE INDEX statement into AST.
Parses a DEFINE INDEX statement into an IndexAST.
Parameters
Section titled “Parameters”string
The raw SurrealQL DEFINE INDEX statement
Returns
Section titled “Returns”Complete IndexAST
Example
Section titled “Example”const index = parseIndexDefinition("DEFINE INDEX email_idx ON TABLE user FIELDS email UNIQUE");// { name: "email_idx", columns: ["email"], unique: true }ast.parseTable()
Section titled “ast.parseTable()”
readonlyparseTable: (ql) =>Partial<TableAST> =parseTableDefinition
Parse a DEFINE TABLE statement into AST.
Parses a DEFINE TABLE statement into a partial TableAST.
Parameters
Section titled “Parameters”string
The raw SurrealQL DEFINE TABLE statement
Returns
Section titled “Returns”Partial<TableAST>
Partial TableAST (fields, indexes, events are populated separately)
Example
Section titled “Example”const table = parseTableDefinition("DEFINE TABLE user SCHEMAFULL");// { name: "user", type: "NORMAL", schemafull: true, ... }clearConfig()
Section titled “clearConfig()”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.
Returns
Section titled “Returns”void
configure()
Section titled “configure()”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 dbconst users = await User.select(db, { limit: 10 });
// After: db is optionalconst users = await User.select({ limit: 10 });Parameters
Section titled “Parameters”options
Section titled “options”Configuration options
Returns
Section titled “Returns”void
Example
Section titled “Example”// Option 1: Pass a pre-connected databaseconst 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; }});Example
Section titled “Example”// With factory function (recommended)Unreal.configure({ getDatabase: () => connectToDatabase() });
// With pre-connected instanceUnreal.configure({ database: db });generateSchema()
Section titled “generateSchema()”
readonlygenerateSchema: (definables,method) =>string=generateFullSchemaQl
Generate full SurrealQL schema from definitions.
Generates the full SurrealQL schema for all provided definable entities (tables and indexes).
Parameters
Section titled “Parameters”definables
Section titled “definables”Definable[]
An array of Definable entities (model classes and index definitions).
method
Section titled “method”The method to use for schema application if a table already exists.
"IF NOT EXISTS" | "OVERWRITE" | "error"
Returns
Section titled “Returns”string
A string containing the complete SurrealQL schema.
Example
Section titled “Example”const ddl = Unreal.generateSchema([User, Post]);console.log(ddl);// DEFINE TABLE user SCHEMAFULL;// DEFINE FIELD email ON user TYPE string;// ...getDatabase()
Section titled “getDatabase()”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.
Returns
Section titled “Returns”Promise<SurrealLike>
The database instance
Throws
Section titled “Throws”Error if no database is configured
Example
Section titled “Example”// In a custom model methodclass User extends Table.normal(...) { async customMethod() { const db = await getDatabase(); return db.query(surql`SELECT * FROM user WHERE active = true`); }}Throws
Section titled “Throws”Error if no database is configured
hasDatabase()
Section titled “hasDatabase()”hasDatabase: () =>
boolean
Check if a database is configured.
Checks if a database is configured (either directly or via factory).
Returns
Section titled “Returns”boolean
true if a database is configured