@coasys/ad4m / Exports / Ad4mModel
Class: Ad4mModel
Base class for defining data models in AD4M.
Description
Ad4mModel provides the foundation for creating data models that are stored in AD4M perspectives. Each model instance is represented as a subgraph in the perspective, with properties and collections mapped to links in that graph. The class uses Prolog-based queries to efficiently search and filter instances based on their properties and relationships.
Key concepts:
- Each model instance has a unique base expression that serves as its identifier
- Properties are stored as links with predicates defined by the
throughoption - Collections represent one-to-many relationships as sets of links
- Queries are translated to Prolog for efficient graph pattern matching
- Changes are tracked through the perspective's subscription system
Example
// Define a recipe model
@ModelOptions({ name: "Recipe" })
class Recipe extends Ad4mModel {
// Required property with literal value
@Property({
through: "recipe://name",
resolveLanguage: "literal"
})
name: string = "";
// Optional property with custom initial value
@Optional({
through: "recipe://status",
initial: "recipe://draft"
})
status: string = "";
// Read-only computed property
@ReadOnly({
through: "recipe://rating",
getter: `
findall(Rating, triple(Base, "recipe://user_rating", Rating), Ratings),
sum_list(Ratings, Sum),
length(Ratings, Count),
Value is Sum / Count
`
})
averageRating: number = 0;
// Collection of ingredients
@Collection({ through: "recipe://ingredient" })
ingredients: string[] = [];
// Collection of comments that are instances of another model
@Collection({
through: "recipe://comment",
where: { isInstance: Comment }
})
comments: Comment[] = [];
}
// Create and save a new recipe
const recipe = new Recipe(perspective);
recipe.name = "Chocolate Cake";
recipe.ingredients = ["flour", "sugar", "cocoa"];
await recipe.save();
// Query recipes in different ways
// Get all recipes
const allRecipes = await Recipe.findAll(perspective);
// Find recipes with specific criteria
const desserts = await Recipe.findAll(perspective, {
where: {
status: "recipe://published",
averageRating: { gt: 4 }
},
order: { name: "ASC" },
limit: 10
});
// Use the fluent query builder
const popularRecipes = await Recipe.query(perspective)
.where({ averageRating: { gt: 4.5 } })
.order({ averageRating: "DESC" })
.limit(5)
.get();
// Subscribe to real-time updates
await Recipe.query(perspective)
.where({ status: "recipe://cooking" })
.subscribe(recipes => {
console.log("Currently being cooked:", recipes);
});
// Paginate results
const { results, totalCount, pageNumber } = await Recipe.query(perspective)
.where({ status: "recipe://published" })
.paginate(10, 1);Table of contents
Constructors
Properties
Accessors
Methods
- cleanCopy
- delete
- get
- getData
- innerUpdate
- save
- setCollectionAdder
- setCollectionRemover
- setCollectionSetter
- setProperty
- update
- assignValuesToInstance
- buildGraphTraversalWhereClause
- buildSurrealSelectFields
- buildSurrealSelectFieldsWithAggregation
- buildSurrealWhereClause
- count
- countQueryToProlog
- countQueryToSurrealQL
- determineNamespace
- determinePredicate
- findAll
- findAllAndCount
- formatSurrealValue
- fromJSONSchema
- getClassName
- getDefaultValueForType
- getModelMetadata
- getPropertyOption
- instancesFromPrologResult
- matchesCondition
- paginate
- query
- queryToProlog
- queryToSurrealQL
Constructors
constructor
• new Ad4mModel(perspective, baseExpression?, source?)
Constructs a new model instance.
Parameters
| Name | Type | Description |
|---|---|---|
perspective | PerspectiveProxy | The perspective where this model will be stored |
baseExpression? | string | Optional unique identifier for this instance |
source? | string | Optional source expression this instance is linked to |
Example
// Create a new recipe with auto-generated base expression
const recipe = new Recipe(perspective);
// Create with specific base expression
const recipe = new Recipe(perspective, "recipe://chocolate-cake");
// Create with source link
const recipe = new Recipe(perspective, undefined, "cookbook://desserts");Defined in
model/Ad4mModel.ts:596 (opens in a new tab)
Properties
#baseExpression
• Private #baseExpression: string
Defined in
model/Ad4mModel.ts:406 (opens in a new tab)
#perspective
• Private #perspective: PerspectiveProxy
Defined in
model/Ad4mModel.ts:409 (opens in a new tab)
#source
• Private #source: string
Defined in
model/Ad4mModel.ts:408 (opens in a new tab)
#subjectClassName
• Private #subjectClassName: string
Defined in
model/Ad4mModel.ts:407 (opens in a new tab)
author
• author: string
Defined in
model/Ad4mModel.ts:410 (opens in a new tab)
timestamp
• timestamp: string
Defined in
model/Ad4mModel.ts:411 (opens in a new tab)
classNamesByClass
▪ Static Private classNamesByClass: WeakMap<typeof Ad4mModel, { [perspectiveId: string]: string; }>
Defined in
model/Ad4mModel.ts:413 (opens in a new tab)
Accessors
baseExpression
• get baseExpression(): string
Gets the base expression of the subject.
Returns
string
Defined in
model/Ad4mModel.ts:605 (opens in a new tab)
perspective
• Protected get perspective(): PerspectiveProxy
Protected getter for the perspective. Allows subclasses to access the perspective while keeping it private from external code.
Returns
Defined in
model/Ad4mModel.ts:613 (opens in a new tab)
Methods
cleanCopy
▸ Private cleanCopy(): Object
Returns
Object
Defined in
model/Ad4mModel.ts:1974 (opens in a new tab)
delete
▸ delete(batchId?): Promise<void>
Deletes the model instance from the perspective.
Parameters
| Name | Type | Description |
|---|---|---|
batchId? | string | Optional batch ID for batch operations |
Returns
Promise<void>
Throws
Will throw if removal fails
Example
const recipe = await Recipe.findAll(perspective)[0];
await recipe.delete();
// Or with batch operations:
const batchId = await perspective.createBatch();
await recipe.delete(batchId);
await perspective.commitBatch(batchId);Defined in
model/Ad4mModel.ts:2077 (opens in a new tab)
get
▸ get(): Promise<Ad4mModel>
Gets the model instance with all properties and collections populated.
Returns
Promise<Ad4mModel>
The populated model instance
Throws
Will throw if data retrieval fails
Example
const recipe = new Recipe(perspective, existingId);
await recipe.get();
console.log(recipe.name, recipe.ingredients);Defined in
model/Ad4mModel.ts:2054 (opens in a new tab)
getData
▸ Private getData(): Promise<Ad4mModel>
Returns
Promise<Ad4mModel>
Defined in
model/Ad4mModel.ts:669 (opens in a new tab)
innerUpdate
▸ Private innerUpdate(setProperties?, batchId?): Promise<void>
Parameters
| Name | Type | Default value |
|---|---|---|
setProperties | boolean | true |
batchId? | string | undefined |
Returns
Promise<void>
Defined in
model/Ad4mModel.ts:1985 (opens in a new tab)
save
▸ save(batchId?): Promise<void>
Saves the model instance to the perspective. Creates a new instance with the base expression and links it to the source.
Parameters
| Name | Type | Description |
|---|---|---|
batchId? | string | Optional batch ID for batch operations |
Returns
Promise<void>
Throws
Will throw if instance creation, linking, or updating fails
Example
const recipe = new Recipe(perspective);
recipe.name = "Spaghetti";
recipe.ingredients = ["pasta", "tomato sauce"];
await recipe.save();
// Or with batch operations:
const batchId = await perspective.createBatch();
await recipe.save(batchId);
await perspective.commitBatch(batchId);Defined in
model/Ad4mModel.ts:1928 (opens in a new tab)
setCollectionAdder
▸ Private setCollectionAdder(key, value, batchId?): Promise<void>
Parameters
| Name | Type |
|---|---|
key | string |
value | any |
batchId? | string |
Returns
Promise<void>
Defined in
model/Ad4mModel.ts:1864 (opens in a new tab)
setCollectionRemover
▸ Private setCollectionRemover(key, value, batchId?): Promise<void>
Parameters
| Name | Type |
|---|---|
key | string |
value | any |
batchId? | string |
Returns
Promise<void>
Defined in
model/Ad4mModel.ts:1886 (opens in a new tab)
setCollectionSetter
▸ Private setCollectionSetter(key, value, batchId?): Promise<void>
Parameters
| Name | Type |
|---|---|
key | string |
value | any |
batchId? | string |
Returns
Promise<void>
Defined in
model/Ad4mModel.ts:1840 (opens in a new tab)
setProperty
▸ Private setProperty(key, value, batchId?): Promise<void>
Parameters
| Name | Type |
|---|---|
key | string |
value | any |
batchId? | string |
Returns
Promise<void>
Defined in
model/Ad4mModel.ts:1819 (opens in a new tab)
update
▸ update(batchId?): Promise<void>
Updates the model instance's properties and collections.
Parameters
| Name | Type | Description |
|---|---|---|
batchId? | string | Optional batch ID for batch operations |
Returns
Promise<void>
Throws
Will throw if property setting or collection updates fail
Example
const recipe = await Recipe.findAll(perspective)[0];
recipe.rating = 5;
recipe.ingredients.push("garlic");
await recipe.update();
// Or with batch operations:
const batchId = await perspective.createBatch();
await recipe.update(batchId);
await perspective.commitBatch(batchId);Defined in
model/Ad4mModel.ts:2036 (opens in a new tab)
assignValuesToInstance
▸ Static assignValuesToInstance(perspective, instance, values): Promise<void>
Parameters
| Name | Type |
|---|---|
perspective | PerspectiveProxy |
instance | Ad4mModel |
values | ValueTuple[] |
Returns
Promise<void>
Defined in
model/Ad4mModel.ts:617 (opens in a new tab)
buildGraphTraversalWhereClause
▸ Static Private buildGraphTraversalWhereClause(metadata, where?): string
Builds the WHERE clause for SurrealQL queries using graph traversal syntax.
Parameters
| Name | Type | Description |
|---|---|---|
metadata | ModelMetadata | Model metadata containing property predicates |
where? | Where | Where conditions from the query |
Returns
string
Graph traversal WHERE clause filters, or empty string if no conditions
Description
Translates where conditions into graph traversal filters: ->link[WHERE ...]
This is more efficient than nested SELECTs because SurrealDB can optimize graph traversals.
Handles several condition types:
- Simple equality:
{ name: "Pasta" }→->link[WHERE predicate = 'X' AND out.uri = 'Pasta'] - Arrays (IN clause):
{ name: ["Pasta", "Pizza"] }→->link[WHERE predicate = 'X' AND out.uri IN [...]] - NOT operators: Use
NOTprefix - Comparison operators (gt, gte, lt, lte, etc.): Handled in post-query JavaScript filtering
- Special fields: base uses
uridirectly, author/timestamp handled post-query
Defined in
model/Ad4mModel.ts:854 (opens in a new tab)
buildSurrealSelectFields
▸ Static Private buildSurrealSelectFields(metadata, properties?, collections?): string
Builds the SELECT fields for SurrealQL queries.
Parameters
| Name | Type | Description |
|---|---|---|
metadata | ModelMetadata | Model metadata containing property and collection predicates |
properties? | string[] | Optional array of property names to include (default: all) |
collections? | string[] | Optional array of collection names to include (default: all) |
Returns
string
Comma-separated SELECT field list
Description
Generates the field list for the SELECT clause, resolving properties and collections via subqueries. Each property is fetched with a subquery that finds the link with the appropriate predicate and returns its target. Collections are similar but don't use LIMIT 1.
Field types:
- Properties:
(SELECT VALUE target FROM link WHERE source = $parent.base AND predicate = 'X' LIMIT 1) AS propName - Collections:
(SELECT VALUE target FROM link WHERE source = $parent.base AND predicate = 'X') AS collName - Author/Timestamp: Always included to provide metadata about each instance
If properties or collections arrays are provided, only those fields are included. Otherwise, all properties/collections from metadata are included.
Defined in
model/Ad4mModel.ts:1114 (opens in a new tab)
buildSurrealSelectFieldsWithAggregation
▸ Static Private buildSurrealSelectFieldsWithAggregation(metadata, properties?, collections?): string
Builds the SELECT fields for SurrealQL queries using aggregation functions. Compatible with GROUP BY source queries.
Parameters
| Name | Type |
|---|---|
metadata | ModelMetadata |
properties? | string[] |
collections? | string[] |
Returns
string
Defined in
model/Ad4mModel.ts:1150 (opens in a new tab)
buildSurrealWhereClause
▸ Static Private buildSurrealWhereClause(metadata, where?): string
Builds the WHERE clause for SurrealQL queries.
Parameters
| Name | Type | Description |
|---|---|---|
metadata | ModelMetadata | Model metadata containing property predicates |
where? | Where | Where conditions from the query |
Returns
string
WHERE clause string (without the "WHERE" keyword), or empty string if no conditions
Description
Translates the where conditions from the Query object into SurrealQL WHERE clause fragments. For each property filter, generates a subquery that checks for links with the appropriate predicate and target value.
Handles several condition types:
- Simple equality:
{ name: "Pasta" }→ subquery checking for predicate and target match - Arrays (IN clause):
{ name: ["Pasta", "Pizza"] }→ target IN [...] - Operators:
{ rating: { gt: 4 } }→ target > '4'- gt, gte, lt, lte: comparison operators
- not: negation (single value or array)
- between: range check
- contains: substring/element check (uses SurrealQL CONTAINS)
- Special fields: base, author, timestamp are accessed directly, not via subqueries
All conditions are joined with AND.
Defined in
model/Ad4mModel.ts:985 (opens in a new tab)
count
▸ Static count(perspective, query?, useSurrealDB?): any
Gets a count of all matching instances.
Parameters
| Name | Type | Default value | Description |
|---|---|---|---|
perspective | PerspectiveProxy | undefined | The perspective to search in |
query | Query | {} | Optional query parameters to filter results |
useSurrealDB | boolean | true | Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy) |
Returns
any
Total count of matching entities
Example
const totalRecipes = await Recipe.count(perspective);
const activeRecipes = await Recipe.count(perspective, {
where: { status: "active" }
});
// Use Prolog explicitly (legacy)
const countProlog = await Recipe.count(perspective, {}, false);Defined in
model/Ad4mModel.ts:1804 (opens in a new tab)
countQueryToProlog
▸ Static countQueryToProlog(perspective, query?, modelClassName?): Promise<string>
Parameters
| Name | Type |
|---|---|
perspective | PerspectiveProxy |
query | Query |
modelClassName? | string |
Returns
Promise<string>
Defined in
model/Ad4mModel.ts:1749 (opens in a new tab)
countQueryToSurrealQL
▸ Static Private countQueryToSurrealQL(perspective, query): Promise<string>
Generates a SurrealQL COUNT query for the model.
Parameters
| Name | Type | Description |
|---|---|---|
perspective | PerspectiveProxy | The perspective context |
query | Query | Query parameters to filter the count |
Returns
Promise<string>
SurrealQL COUNT query string
Defined in
model/Ad4mModel.ts:1776 (opens in a new tab)
determineNamespace
▸ Static Private determineNamespace(schema, options): string
Determines the namespace for predicates using cascading precedence
Parameters
| Name | Type |
|---|---|
schema | JSONSchema |
options | JSONSchemaToModelOptions |
Returns
string
Defined in
model/Ad4mModel.ts:2341 (opens in a new tab)
determinePredicate
▸ Static Private determinePredicate(schema, propertyName, propertySchema, namespace, options): string
Determines the predicate for a specific property using cascading precedence
Parameters
| Name | Type |
|---|---|
schema | JSONSchema |
propertyName | string |
propertySchema | JSONSchemaProperty |
namespace | string |
options | JSONSchemaToModelOptions |
Returns
string
Defined in
model/Ad4mModel.ts:2385 (opens in a new tab)
findAll
▸ Static findAll<T>(this, perspective, query?, useSurrealDB?): Promise<T[]>
Gets all instances of the model in the perspective that match the query params.
Type parameters
| Name | Type |
|---|---|
T | extends Ad4mModel<T> |
Parameters
| Name | Type | Default value | Description |
|---|---|---|---|
this | typeof Ad4mModel & (...args: any[]) => T | undefined | - |
perspective | PerspectiveProxy | undefined | The perspective to search in |
query | Query | {} | Optional query parameters to filter results |
useSurrealDB | boolean | true | Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy) |
Returns
Promise<T[]>
Array of matching models
Example
// Get all recipes (uses SurrealDB by default)
const allRecipes = await Recipe.findAll(perspective);
// Get recipes with specific criteria (uses SurrealDB)
const recipes = await Recipe.findAll(perspective, {
where: {
name: "Pasta",
rating: { gt: 4 }
},
order: { createdAt: "DESC" },
limit: 10
});
// Explicitly use Prolog (legacy, for backward compatibility)
const recipesProlog = await Recipe.findAll(perspective, {}, false);Defined in
model/Ad4mModel.ts:1650 (opens in a new tab)
findAllAndCount
▸ Static findAllAndCount<T>(this, perspective, query?, useSurrealDB?): Promise<ResultsWithTotalCount<T>>
Gets all instances with count of total matches without offset & limit applied.
Type parameters
| Name | Type |
|---|---|
T | extends Ad4mModel<T> |
Parameters
| Name | Type | Default value | Description |
|---|---|---|---|
this | typeof Ad4mModel & (...args: any[]) => T | undefined | - |
perspective | PerspectiveProxy | undefined | The perspective to search in |
query | Query | {} | Optional query parameters to filter results |
useSurrealDB | boolean | true | Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy) |
Returns
Promise<ResultsWithTotalCount<T>>
Object containing results array and total count
Example
const { results, totalCount } = await Recipe.findAllAndCount(perspective, {
where: { category: "Dessert" },
limit: 10
});
console.log(`Showing 10 of ${totalCount} dessert recipes`);
// Use Prolog explicitly (legacy)
const { results, totalCount } = await Recipe.findAllAndCount(perspective, {}, false);Defined in
model/Ad4mModel.ts:1689 (opens in a new tab)
formatSurrealValue
▸ Static Private formatSurrealValue(value): string
Formats a value for use in SurrealQL queries.
Parameters
| Name | Type | Description |
|---|---|---|
value | any | The value to format |
Returns
string
Formatted value string ready for SurrealQL
Description
Handles different value types:
- Strings: Wrapped in single quotes with backslash-escaped special characters
- Numbers/booleans: Converted to string
- Arrays: Recursively formatted and wrapped in brackets
Defined in
model/Ad4mModel.ts:1195 (opens in a new tab)
fromJSONSchema
▸ Static fromJSONSchema(schema, options): typeof Ad4mModel
Creates an Ad4mModel class from a JSON Schema definition.
Parameters
| Name | Type | Description |
|---|---|---|
schema | JSONSchema | JSON Schema definition |
options | JSONSchemaToModelOptions | Configuration options |
Returns
typeof Ad4mModel
Generated Ad4mModel subclass
Description
This method dynamically generates an Ad4mModel subclass from a JSON Schema, enabling integration with systems that use JSON Schema for type definitions.
The method follows a cascading approach for determining predicates:
- Explicit configuration in options parameter (highest precedence)
- x-ad4m metadata in the JSON Schema
- Inference from schema title and property names
- Error if no namespace can be determined
Example
// With explicit configuration
const PersonClass = Ad4mModel.fromJSONSchema(schema, {
name: "Person",
namespace: "person://",
resolveLanguage: "literal"
});
// With property mapping
const ContactClass = Ad4mModel.fromJSONSchema(schema, {
name: "Contact",
namespace: "contact://",
propertyMapping: {
"name": "foaf://name",
"email": "foaf://mbox"
}
});
// With x-ad4m metadata in schema
const schema = {
"title": "Product",
"x-ad4m": { "namespace": "product://" },
"properties": {
"name": {
"type": "string",
"x-ad4m": { "through": "product://title" }
}
}
};
const ProductClass = Ad4mModel.fromJSONSchema(schema, { name: "Product" });Throws
Error when namespace cannot be inferred
Defined in
model/Ad4mModel.ts:2163 (opens in a new tab)
getClassName
▸ Static getClassName(perspective): Promise<string>
Parameters
| Name | Type |
|---|---|
perspective | PerspectiveProxy |
Returns
Promise<string>
Defined in
model/Ad4mModel.ts:415 (opens in a new tab)
getDefaultValueForType
▸ Static Private getDefaultValueForType(type?): any
Gets default value for a JSON Schema type
Parameters
| Name | Type |
|---|---|
type? | string |
Returns
any
Defined in
model/Ad4mModel.ts:2462 (opens in a new tab)
getModelMetadata
▸ Static getModelMetadata(): ModelMetadata
Extracts metadata from decorators for query building.
Returns
Structured metadata object containing className, properties, and collections
Description
This method reads the metadata stored by decorators (@Property, @Collection, etc.) and returns it in a structured format that's easier to work with for query builders and other systems that need to introspect model structure.
The metadata includes:
- Class name from
Model Options
- Property metadata (predicates, types, constraints, etc.)
- Collection metadata (predicates, filters, etc.)
For models created via fromJSONSchema(), this method will derive metadata from
the stored __properties and __collections structures that were populated during
the dynamic class creation. If these structures are empty but a JSON schema was
attached to the class, it can fall back to deriving metadata from that schema.
Throws
Error if the class doesn't have
Model Options
decorator
Example
@ModelOptions({ name: "Recipe" })
class Recipe extends Ad4mModel {
@Property({ through: "recipe://name", resolveLanguage: "literal" })
name: string = "";
@Collection({ through: "recipe://ingredient" })
ingredients: string[] = [];
}
const metadata = Recipe.getModelMetadata();
console.log(metadata.className); // "Recipe"
console.log(metadata.properties.name.predicate); // "recipe://name"
console.log(metadata.collections.ingredients.predicate); // "recipe://ingredient"Defined in
model/Ad4mModel.ts:478 (opens in a new tab)
getPropertyOption
▸ Static Private getPropertyOption(propertyName, propertySchema, options, optionName, defaultValue?): any
Gets property-specific options using cascading precedence
Parameters
| Name | Type |
|---|---|
propertyName | string |
propertySchema | JSONSchemaProperty |
options | JSONSchemaToModelOptions |
optionName | keyof PropertyOptions |
defaultValue? | any |
Returns
any
Defined in
model/Ad4mModel.ts:2433 (opens in a new tab)
instancesFromPrologResult
▸ Static instancesFromPrologResult<T>(this, perspective, query, result): Promise<ResultsWithTotalCount<T>>
Type parameters
| Name | Type |
|---|---|
T | extends Ad4mModel<T> |
Parameters
| Name | Type |
|---|---|
this | typeof Ad4mModel & (...args: any[]) => T |
perspective | PerspectiveProxy |
query | Query |
result | AllInstancesResult |
Returns
Promise<ResultsWithTotalCount<T>>
Defined in
model/Ad4mModel.ts:1215 (opens in a new tab)
matchesCondition
▸ Static Private matchesCondition(value, condition): boolean
Checks if a value matches a condition (for post-query filtering).
Parameters
| Name | Type |
|---|---|
value | any |
condition | WhereCondition |
Returns
boolean
Defined in
model/Ad4mModel.ts:1562 (opens in a new tab)
paginate
▸ Static paginate<T>(this, perspective, pageSize, pageNumber, query?, useSurrealDB?): Promise<PaginationResult<T>>
Helper function for pagination with explicit page size and number.
Type parameters
| Name | Type |
|---|---|
T | extends Ad4mModel<T> |
Parameters
| Name | Type | Default value | Description |
|---|---|---|---|
this | typeof Ad4mModel & (...args: any[]) => T | undefined | - |
perspective | PerspectiveProxy | undefined | The perspective to search in |
pageSize | number | undefined | Number of items per page |
pageNumber | number | undefined | Which page to retrieve (1-based) |
query? | Query | undefined | Optional additional query parameters |
useSurrealDB | boolean | true | Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy) |
Returns
Promise<PaginationResult<T>>
Paginated results with metadata
Example
const page = await Recipe.paginate(perspective, 10, 1, {
where: { category: "Main Course" }
});
console.log(`Page ${page.pageNumber} of recipes, ${page.results.length} items`);
// Use Prolog explicitly (legacy)
const pageProlog = await Recipe.paginate(perspective, 10, 1, {}, false);Defined in
model/Ad4mModel.ts:1727 (opens in a new tab)
query
▸ Static query<T>(this, perspective, query?): ModelQueryBuilder<T>
Creates a query builder for fluent query construction.
Type parameters
| Name | Type |
|---|---|
T | extends Ad4mModel<T> |
Parameters
| Name | Type | Description |
|---|---|---|
this | typeof Ad4mModel & (...args: any[]) => T | - |
perspective | PerspectiveProxy | The perspective to query |
query? | Query | Optional initial query parameters |
Returns
A new query builder instance
Example
const recipes = await Recipe.query(perspective)
.where({ category: "Dessert" })
.order({ rating: "DESC" })
.limit(5)
.run();
// With real-time updates
await Recipe.query(perspective)
.where({ status: "cooking" })
.subscribe(recipes => {
console.log("Currently cooking:", recipes);
});Defined in
model/Ad4mModel.ts:2104 (opens in a new tab)
queryToProlog
▸ Static queryToProlog(perspective, query, modelClassName?): Promise<string>
Parameters
| Name | Type |
|---|---|
perspective | PerspectiveProxy |
query | Query |
modelClassName? | string |
Returns
Promise<string>
Defined in
model/Ad4mModel.ts:689 (opens in a new tab)
queryToSurrealQL
▸ Static queryToSurrealQL(perspective, query): Promise<string>
Generates a SurrealQL query from a Query object.
Parameters
| Name | Type | Description |
|---|---|---|
perspective | PerspectiveProxy | The perspective to query (used for metadata extraction) |
query | Query | Query parameters (where, order, limit, offset, properties, collections) |
Returns
Promise<string>
Complete SurrealQL query string ready for execution
Description
This method translates high-level query parameters into a SurrealQL query string that can be executed against the SurrealDB backend. Unlike Prolog queries which operate on SDNA-aware predicates, SurrealQL queries operate directly on raw links stored in SurrealDB.
The generated query uses a CTE (Common Table Expression) pattern:
- First, identify candidate base expressions by filtering links based on where conditions
- Then, for each candidate base, resolve properties and collections via subqueries
- Finally, apply ordering, pagination (LIMIT/START) at the SQL level
Key architectural notes:
- SurrealDB stores only raw links (source, predicate, target, author, timestamp)
- No SDNA knowledge at the database level
- Properties are resolved via subqueries that look for links with specific predicates
- Collections are similar but return multiple values instead of one
- Special fields (base, author, timestamp) are accessed directly, not via subqueries
Example
const query = Recipe.queryToSurrealQL(perspective, {
where: { name: "Pasta", rating: { gt: 4 } },
order: { timestamp: "DESC" },
limit: 10
});
// Returns: SELECT source AS base, array::first(target[WHERE predicate = ...]) AS name, ...
// FROM link WHERE ... GROUP BY source ORDER BY timestamp DESC LIMIT 10