@coasys/ad4m 0.10.1-release-candidate-5 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/index.cjs +1716 -87
- package/lib/index.js +1716 -87
- package/lib/src/model/Ad4mModel.d.ts +423 -9
- package/lib/src/model/Ad4mModel.js +1499 -61
- package/lib/src/model/Ad4mModel.test.d.ts +1 -0
- package/lib/src/model/Ad4mModel.test.js +1325 -0
- package/lib/src/perspectives/PerspectiveClient.d.ts +17 -0
- package/lib/src/perspectives/PerspectiveClient.js +61 -0
- package/lib/src/perspectives/PerspectiveProxy.d.ts +52 -1
- package/lib/src/perspectives/PerspectiveProxy.js +157 -28
- package/lib/src/perspectives/PerspectiveResolver.d.ts +1 -0
- package/lib/src/perspectives/PerspectiveResolver.js +11 -0
- package/lib/src/schema.gql +1 -0
- package/lib/src/typeDefs.js +1 -0
- package/package.json +1 -1
- package/src/model/Ad4mModel.test.ts +1476 -0
- package/src/model/Ad4mModel.ts +1758 -87
- package/src/perspectives/PerspectiveClient.ts +67 -0
- package/src/perspectives/PerspectiveProxy.ts +175 -35
- package/src/perspectives/PerspectiveResolver.ts +8 -0
|
@@ -12,8 +12,8 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
|
|
|
12
12
|
var _Ad4mModel_baseExpression, _Ad4mModel_subjectClassName, _Ad4mModel_source, _Ad4mModel_perspective;
|
|
13
13
|
import { Literal } from "../Literal";
|
|
14
14
|
import { Link } from "../links/Links";
|
|
15
|
-
import { makeRandomPrologAtom } from "./decorators";
|
|
16
|
-
import { singularToPlural } from "./util";
|
|
15
|
+
import { makeRandomPrologAtom, ModelOptions } from "./decorators";
|
|
16
|
+
import { singularToPlural, propertyNameToSetterName } from "./util";
|
|
17
17
|
function capitalize(word) {
|
|
18
18
|
return word.charAt(0).toUpperCase() + word.slice(1);
|
|
19
19
|
}
|
|
@@ -149,6 +149,42 @@ function buildLimitQuery(limit) {
|
|
|
149
149
|
return "AllInstances = InstancesWithOffset";
|
|
150
150
|
return `takeN(InstancesWithOffset, ${limit}, AllInstances)`;
|
|
151
151
|
}
|
|
152
|
+
function normalizeNamespaceString(namespace) {
|
|
153
|
+
if (!namespace)
|
|
154
|
+
return '';
|
|
155
|
+
if (namespace.includes('://')) {
|
|
156
|
+
const [scheme, rest] = namespace.split('://');
|
|
157
|
+
const path = (rest || '').replace(/\/+$/, '');
|
|
158
|
+
return `${scheme}://${path}`;
|
|
159
|
+
}
|
|
160
|
+
else {
|
|
161
|
+
return namespace.replace(/\/+$/, '');
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
function normalizeSchemaType(type) {
|
|
165
|
+
if (!type)
|
|
166
|
+
return undefined;
|
|
167
|
+
if (typeof type === "string")
|
|
168
|
+
return type;
|
|
169
|
+
if (Array.isArray(type) && type.length > 0) {
|
|
170
|
+
const nonNull = type.find((t) => t !== "null");
|
|
171
|
+
return nonNull || type[0];
|
|
172
|
+
}
|
|
173
|
+
return undefined;
|
|
174
|
+
}
|
|
175
|
+
function isSchemaType(schema, expectedType) {
|
|
176
|
+
return normalizeSchemaType(schema.type) === expectedType;
|
|
177
|
+
}
|
|
178
|
+
function isArrayType(schema) {
|
|
179
|
+
return isSchemaType(schema, "array");
|
|
180
|
+
}
|
|
181
|
+
function isObjectType(schema) {
|
|
182
|
+
return isSchemaType(schema, "object");
|
|
183
|
+
}
|
|
184
|
+
function isNumericType(schema) {
|
|
185
|
+
const normalized = normalizeSchemaType(schema.type);
|
|
186
|
+
return normalized === "number" || normalized === "integer";
|
|
187
|
+
}
|
|
152
188
|
/**
|
|
153
189
|
* Base class for defining data models in AD4M.
|
|
154
190
|
*
|
|
@@ -269,6 +305,126 @@ export class Ad4mModel {
|
|
|
269
305
|
}
|
|
270
306
|
return classCache[perspectiveID];
|
|
271
307
|
}
|
|
308
|
+
/**
|
|
309
|
+
* Extracts metadata from decorators for query building.
|
|
310
|
+
*
|
|
311
|
+
* @description
|
|
312
|
+
* This method reads the metadata stored by decorators (@Property, @Collection, etc.)
|
|
313
|
+
* and returns it in a structured format that's easier to work with for query builders
|
|
314
|
+
* and other systems that need to introspect model structure.
|
|
315
|
+
*
|
|
316
|
+
* The metadata includes:
|
|
317
|
+
* - Class name from @ModelOptions
|
|
318
|
+
* - Property metadata (predicates, types, constraints, etc.)
|
|
319
|
+
* - Collection metadata (predicates, filters, etc.)
|
|
320
|
+
*
|
|
321
|
+
* For models created via `fromJSONSchema()`, this method will derive metadata from
|
|
322
|
+
* the stored `__properties` and `__collections` structures that were populated during
|
|
323
|
+
* the dynamic class creation. If these structures are empty but a JSON schema was
|
|
324
|
+
* attached to the class, it can fall back to deriving metadata from that schema.
|
|
325
|
+
*
|
|
326
|
+
* @returns Structured metadata object containing className, properties, and collections
|
|
327
|
+
* @throws Error if the class doesn't have @ModelOptions decorator
|
|
328
|
+
*
|
|
329
|
+
* @example
|
|
330
|
+
* ```typescript
|
|
331
|
+
* @ModelOptions({ name: "Recipe" })
|
|
332
|
+
* class Recipe extends Ad4mModel {
|
|
333
|
+
* @Property({ through: "recipe://name", resolveLanguage: "literal" })
|
|
334
|
+
* name: string = "";
|
|
335
|
+
*
|
|
336
|
+
* @Collection({ through: "recipe://ingredient" })
|
|
337
|
+
* ingredients: string[] = [];
|
|
338
|
+
* }
|
|
339
|
+
*
|
|
340
|
+
* const metadata = Recipe.getModelMetadata();
|
|
341
|
+
* console.log(metadata.className); // "Recipe"
|
|
342
|
+
* console.log(metadata.properties.name.predicate); // "recipe://name"
|
|
343
|
+
* console.log(metadata.collections.ingredients.predicate); // "recipe://ingredient"
|
|
344
|
+
* ```
|
|
345
|
+
*/
|
|
346
|
+
static getModelMetadata() {
|
|
347
|
+
// Access the prototype with any type to access decorator-added properties
|
|
348
|
+
const prototype = this.prototype;
|
|
349
|
+
// Validate that the class has @ModelOptions decorator
|
|
350
|
+
// The decorator sets prototype.className, so we check for its existence
|
|
351
|
+
if (!prototype.className || prototype.className === 'Ad4mModel') {
|
|
352
|
+
throw new Error("Model class must be decorated with @ModelOptions");
|
|
353
|
+
}
|
|
354
|
+
// Extract className
|
|
355
|
+
const className = prototype.className;
|
|
356
|
+
// Extract properties from prototype.__properties
|
|
357
|
+
const propertiesMetadata = {};
|
|
358
|
+
const prototypeProperties = prototype.__properties || {};
|
|
359
|
+
for (const [propertyName, opts] of Object.entries(prototypeProperties)) {
|
|
360
|
+
const options = opts;
|
|
361
|
+
propertiesMetadata[propertyName] = {
|
|
362
|
+
name: propertyName,
|
|
363
|
+
predicate: options.through || "",
|
|
364
|
+
required: options.required || false,
|
|
365
|
+
writable: options.writable || false,
|
|
366
|
+
...(options.initial !== undefined && { initial: options.initial }),
|
|
367
|
+
...(options.resolveLanguage !== undefined && { resolveLanguage: options.resolveLanguage }),
|
|
368
|
+
...(options.getter !== undefined && { getter: options.getter }),
|
|
369
|
+
...(options.setter !== undefined && { setter: options.setter }),
|
|
370
|
+
...(options.local !== undefined && { local: options.local }),
|
|
371
|
+
...(options.transform !== undefined && { transform: options.transform }),
|
|
372
|
+
...(options.flag !== undefined && { flag: options.flag })
|
|
373
|
+
};
|
|
374
|
+
}
|
|
375
|
+
// Extract collections from prototype.__collections
|
|
376
|
+
const collectionsMetadata = {};
|
|
377
|
+
const prototypeCollections = prototype.__collections || {};
|
|
378
|
+
for (const [collectionName, opts] of Object.entries(prototypeCollections)) {
|
|
379
|
+
const options = opts;
|
|
380
|
+
collectionsMetadata[collectionName] = {
|
|
381
|
+
name: collectionName,
|
|
382
|
+
predicate: options.through || "",
|
|
383
|
+
...(options.where !== undefined && { where: options.where }),
|
|
384
|
+
...(options.local !== undefined && { local: options.local })
|
|
385
|
+
};
|
|
386
|
+
}
|
|
387
|
+
// Fallback: If both structures are empty but a JSON schema is attached, derive from it
|
|
388
|
+
// This handles edge cases where fromJSONSchema() was called but metadata wasn't properly populated
|
|
389
|
+
const hasProperties = Object.keys(propertiesMetadata).length > 0;
|
|
390
|
+
const hasCollections = Object.keys(collectionsMetadata).length > 0;
|
|
391
|
+
const hasMetadata = hasProperties || hasCollections;
|
|
392
|
+
if (!hasMetadata && prototype.__jsonSchema) {
|
|
393
|
+
// Derive metadata from the attached JSON schema
|
|
394
|
+
const schema = prototype.__jsonSchema;
|
|
395
|
+
const options = prototype.__jsonSchemaOptions || {};
|
|
396
|
+
if (schema.properties) {
|
|
397
|
+
for (const [propertyName, propertySchema] of Object.entries(schema.properties)) {
|
|
398
|
+
const isArray = isArrayType(propertySchema);
|
|
399
|
+
const predicate = this.determinePredicate(schema, propertyName, propertySchema, this.determineNamespace(schema, options), options);
|
|
400
|
+
if (isArray) {
|
|
401
|
+
collectionsMetadata[propertyName] = {
|
|
402
|
+
name: propertyName,
|
|
403
|
+
predicate: predicate,
|
|
404
|
+
...(propertySchema["x-ad4m"]?.local !== undefined && { local: propertySchema["x-ad4m"].local })
|
|
405
|
+
};
|
|
406
|
+
}
|
|
407
|
+
else {
|
|
408
|
+
const isRequired = schema.required?.includes(propertyName) || false;
|
|
409
|
+
propertiesMetadata[propertyName] = {
|
|
410
|
+
name: propertyName,
|
|
411
|
+
predicate: predicate,
|
|
412
|
+
required: isRequired,
|
|
413
|
+
writable: propertySchema["x-ad4m"]?.writable !== false,
|
|
414
|
+
...(propertySchema["x-ad4m"]?.resolveLanguage && { resolveLanguage: propertySchema["x-ad4m"].resolveLanguage }),
|
|
415
|
+
...(propertySchema["x-ad4m"]?.initial && { initial: propertySchema["x-ad4m"].initial }),
|
|
416
|
+
...(propertySchema["x-ad4m"]?.local !== undefined && { local: propertySchema["x-ad4m"].local })
|
|
417
|
+
};
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
return {
|
|
423
|
+
className,
|
|
424
|
+
properties: propertiesMetadata,
|
|
425
|
+
collections: collectionsMetadata
|
|
426
|
+
};
|
|
427
|
+
}
|
|
272
428
|
/**
|
|
273
429
|
* Constructs a new model instance.
|
|
274
430
|
*
|
|
@@ -396,6 +552,477 @@ export class Ad4mModel {
|
|
|
396
552
|
`;
|
|
397
553
|
return fullQuery;
|
|
398
554
|
}
|
|
555
|
+
/**
|
|
556
|
+
* Generates a SurrealQL query from a Query object.
|
|
557
|
+
*
|
|
558
|
+
* @description
|
|
559
|
+
* This method translates high-level query parameters into a SurrealQL query string
|
|
560
|
+
* that can be executed against the SurrealDB backend. Unlike Prolog queries which
|
|
561
|
+
* operate on SDNA-aware predicates, SurrealQL queries operate directly on raw links
|
|
562
|
+
* stored in SurrealDB.
|
|
563
|
+
*
|
|
564
|
+
* The generated query uses a CTE (Common Table Expression) pattern:
|
|
565
|
+
* 1. First, identify candidate base expressions by filtering links based on where conditions
|
|
566
|
+
* 2. Then, for each candidate base, resolve properties and collections via subqueries
|
|
567
|
+
* 3. Finally, apply ordering, pagination (LIMIT/START) at the SQL level
|
|
568
|
+
*
|
|
569
|
+
* Key architectural notes:
|
|
570
|
+
* - SurrealDB stores only raw links (source, predicate, target, author, timestamp)
|
|
571
|
+
* - No SDNA knowledge at the database level
|
|
572
|
+
* - Properties are resolved via subqueries that look for links with specific predicates
|
|
573
|
+
* - Collections are similar but return multiple values instead of one
|
|
574
|
+
* - Special fields (base, author, timestamp) are accessed directly, not via subqueries
|
|
575
|
+
*
|
|
576
|
+
* @param perspective - The perspective to query (used for metadata extraction)
|
|
577
|
+
* @param query - Query parameters (where, order, limit, offset, properties, collections)
|
|
578
|
+
* @returns Complete SurrealQL query string ready for execution
|
|
579
|
+
*
|
|
580
|
+
* @example
|
|
581
|
+
* ```typescript
|
|
582
|
+
* const query = Recipe.queryToSurrealQL(perspective, {
|
|
583
|
+
* where: { name: "Pasta", rating: { gt: 4 } },
|
|
584
|
+
* order: { timestamp: "DESC" },
|
|
585
|
+
* limit: 10
|
|
586
|
+
* });
|
|
587
|
+
* // Returns: SELECT source AS base, array::first(target[WHERE predicate = ...]) AS name, ...
|
|
588
|
+
* // FROM link WHERE ... GROUP BY source ORDER BY timestamp DESC LIMIT 10
|
|
589
|
+
* ```
|
|
590
|
+
*/
|
|
591
|
+
static async queryToSurrealQL(perspective, query) {
|
|
592
|
+
const metadata = this.getModelMetadata();
|
|
593
|
+
const { source, where, order, offset, limit } = query;
|
|
594
|
+
// Build list of graph traversal filters for required predicates
|
|
595
|
+
const graphTraversalFilters = [];
|
|
596
|
+
// Add source filter if specified (filter to nodes that are children of this source)
|
|
597
|
+
// Source filter means: find targets of 'ad4m://has_child' links from the specified source
|
|
598
|
+
if (source) {
|
|
599
|
+
// Use graph traversal: node must be target of has_child link from source
|
|
600
|
+
graphTraversalFilters.push(`count(<-link[WHERE perspective = $perspective AND in.uri = ${this.formatSurrealValue(source)} AND predicate = 'ad4m://has_child']) > 0`);
|
|
601
|
+
}
|
|
602
|
+
// Add filters for required properties
|
|
603
|
+
for (const [propName, propMeta] of Object.entries(metadata.properties)) {
|
|
604
|
+
if (propMeta.required) {
|
|
605
|
+
// For flag properties, also filter by the target value
|
|
606
|
+
if (propMeta.flag && propMeta.initial) {
|
|
607
|
+
graphTraversalFilters.push(`count(->link[WHERE perspective = $perspective AND predicate = '${propMeta.predicate}' AND out.uri = '${propMeta.initial}']) > 0`);
|
|
608
|
+
}
|
|
609
|
+
else {
|
|
610
|
+
graphTraversalFilters.push(`count(->link[WHERE perspective = $perspective AND predicate = '${propMeta.predicate}']) > 0`);
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
// If no required properties, we need at least one property to define the model
|
|
615
|
+
// Use any property with an initial value as the defining characteristic
|
|
616
|
+
if (graphTraversalFilters.length === 0) {
|
|
617
|
+
for (const [propName, propMeta] of Object.entries(metadata.properties)) {
|
|
618
|
+
if (propMeta.initial) {
|
|
619
|
+
// For flag properties, also filter by the target value
|
|
620
|
+
if (propMeta.flag) {
|
|
621
|
+
graphTraversalFilters.push(`count(->link[WHERE perspective = $perspective AND predicate = '${propMeta.predicate}' AND out.uri = '${propMeta.initial}']) > 0`);
|
|
622
|
+
}
|
|
623
|
+
else {
|
|
624
|
+
graphTraversalFilters.push(`count(->link[WHERE perspective = $perspective AND predicate = '${propMeta.predicate}']) > 0`);
|
|
625
|
+
}
|
|
626
|
+
break; // Just need one defining property
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
// Build user WHERE clause filters using graph traversal
|
|
631
|
+
const userWhereClause = this.buildGraphTraversalWhereClause(metadata, where);
|
|
632
|
+
// Build complete WHERE clause using graph traversal filters
|
|
633
|
+
const whereConditions = [];
|
|
634
|
+
// Add all graph traversal filters for required properties
|
|
635
|
+
whereConditions.push(...graphTraversalFilters);
|
|
636
|
+
// Add user where conditions if any
|
|
637
|
+
if (userWhereClause) {
|
|
638
|
+
whereConditions.push(userWhereClause);
|
|
639
|
+
}
|
|
640
|
+
// Always ensure node has at least one link in this perspective
|
|
641
|
+
whereConditions.push(`count(->link[WHERE perspective = $perspective]) > 0`);
|
|
642
|
+
// Build the query FROM node using direct graph traversal in WHERE
|
|
643
|
+
// This avoids slow subqueries and uses graph indexes for fast traversal
|
|
644
|
+
const fullQuery = `
|
|
645
|
+
SELECT
|
|
646
|
+
id AS source,
|
|
647
|
+
uri AS source_uri,
|
|
648
|
+
->link[WHERE perspective = $perspective] AS links
|
|
649
|
+
FROM node
|
|
650
|
+
WHERE ${whereConditions.join(' AND ')}
|
|
651
|
+
`.trim();
|
|
652
|
+
return fullQuery;
|
|
653
|
+
}
|
|
654
|
+
/**
|
|
655
|
+
* Builds the WHERE clause for SurrealQL queries using graph traversal syntax.
|
|
656
|
+
*
|
|
657
|
+
* @description
|
|
658
|
+
* Translates where conditions into graph traversal filters: `->link[WHERE ...]`
|
|
659
|
+
* This is more efficient than nested SELECTs because SurrealDB can optimize graph traversals.
|
|
660
|
+
*
|
|
661
|
+
* Handles several condition types:
|
|
662
|
+
* - Simple equality: `{ name: "Pasta" }` → `->link[WHERE predicate = 'X' AND out.uri = 'Pasta']`
|
|
663
|
+
* - Arrays (IN clause): `{ name: ["Pasta", "Pizza"] }` → `->link[WHERE predicate = 'X' AND out.uri IN [...]]`
|
|
664
|
+
* - NOT operators: Use `NOT` prefix
|
|
665
|
+
* - Comparison operators (gt, gte, lt, lte, etc.): Handled in post-query JavaScript filtering
|
|
666
|
+
* - Special fields: base uses `uri` directly, author/timestamp handled post-query
|
|
667
|
+
*
|
|
668
|
+
* @param metadata - Model metadata containing property predicates
|
|
669
|
+
* @param where - Where conditions from the query
|
|
670
|
+
* @returns Graph traversal WHERE clause filters, or empty string if no conditions
|
|
671
|
+
*
|
|
672
|
+
* @private
|
|
673
|
+
*/
|
|
674
|
+
static buildGraphTraversalWhereClause(metadata, where) {
|
|
675
|
+
if (!where)
|
|
676
|
+
return '';
|
|
677
|
+
const conditions = [];
|
|
678
|
+
for (const [propertyName, condition] of Object.entries(where)) {
|
|
679
|
+
// Check if this is a special field (base, author, timestamp)
|
|
680
|
+
// Note: author and timestamp filtering is done in JavaScript after query
|
|
681
|
+
const isSpecial = ['base', 'author', 'timestamp'].includes(propertyName);
|
|
682
|
+
if (isSpecial) {
|
|
683
|
+
// Skip author and timestamp - they'll be filtered in JavaScript
|
|
684
|
+
// Only handle 'base' (which maps to 'uri') here
|
|
685
|
+
if (propertyName === 'author' || propertyName === 'timestamp') {
|
|
686
|
+
continue; // Skip - will be filtered post-query
|
|
687
|
+
}
|
|
688
|
+
const columnName = 'uri'; // base maps to uri in node table
|
|
689
|
+
// Handle base/uri field directly
|
|
690
|
+
if (Array.isArray(condition)) {
|
|
691
|
+
// Array values (IN clause)
|
|
692
|
+
const formattedValues = condition.map(v => this.formatSurrealValue(v)).join(', ');
|
|
693
|
+
conditions.push(`${columnName} IN [${formattedValues}]`);
|
|
694
|
+
}
|
|
695
|
+
else if (typeof condition === 'object' && condition !== null) {
|
|
696
|
+
// Operator object
|
|
697
|
+
const ops = condition;
|
|
698
|
+
if (ops.not !== undefined) {
|
|
699
|
+
if (Array.isArray(ops.not)) {
|
|
700
|
+
const formattedValues = ops.not.map(v => this.formatSurrealValue(v)).join(', ');
|
|
701
|
+
conditions.push(`${columnName} NOT IN [${formattedValues}]`);
|
|
702
|
+
}
|
|
703
|
+
else {
|
|
704
|
+
conditions.push(`${columnName} != ${this.formatSurrealValue(ops.not)}`);
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
if (ops.between !== undefined && Array.isArray(ops.between) && ops.between.length === 2) {
|
|
708
|
+
conditions.push(`${columnName} >= ${this.formatSurrealValue(ops.between[0])} AND ${columnName} <= ${this.formatSurrealValue(ops.between[1])}`);
|
|
709
|
+
}
|
|
710
|
+
if (ops.gt !== undefined) {
|
|
711
|
+
conditions.push(`${columnName} > ${this.formatSurrealValue(ops.gt)}`);
|
|
712
|
+
}
|
|
713
|
+
if (ops.gte !== undefined) {
|
|
714
|
+
conditions.push(`${columnName} >= ${this.formatSurrealValue(ops.gte)}`);
|
|
715
|
+
}
|
|
716
|
+
if (ops.lt !== undefined) {
|
|
717
|
+
conditions.push(`${columnName} < ${this.formatSurrealValue(ops.lt)}`);
|
|
718
|
+
}
|
|
719
|
+
if (ops.lte !== undefined) {
|
|
720
|
+
conditions.push(`${columnName} <= ${this.formatSurrealValue(ops.lte)}`);
|
|
721
|
+
}
|
|
722
|
+
if (ops.contains !== undefined) {
|
|
723
|
+
conditions.push(`${columnName} CONTAINS ${this.formatSurrealValue(ops.contains)}`);
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
else {
|
|
727
|
+
// Simple equality
|
|
728
|
+
conditions.push(`${columnName} = ${this.formatSurrealValue(condition)}`);
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
else {
|
|
732
|
+
// Handle regular properties via graph traversal
|
|
733
|
+
const propMeta = metadata.properties[propertyName];
|
|
734
|
+
if (!propMeta)
|
|
735
|
+
continue; // Skip if property not found in metadata
|
|
736
|
+
const predicate = propMeta.predicate;
|
|
737
|
+
// Use fn::parse_literal() for properties with resolveLanguage
|
|
738
|
+
const targetField = propMeta.resolveLanguage === 'literal' ? 'fn::parse_literal(out.uri)' : 'out.uri';
|
|
739
|
+
if (Array.isArray(condition)) {
|
|
740
|
+
// Array values (IN clause)
|
|
741
|
+
const formattedValues = condition.map(v => this.formatSurrealValue(v)).join(', ');
|
|
742
|
+
conditions.push(`count(->link[WHERE perspective = $perspective AND predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) > 0`);
|
|
743
|
+
}
|
|
744
|
+
else if (typeof condition === 'object' && condition !== null) {
|
|
745
|
+
// Operator object
|
|
746
|
+
const ops = condition;
|
|
747
|
+
if (ops.not !== undefined) {
|
|
748
|
+
if (Array.isArray(ops.not)) {
|
|
749
|
+
// For NOT IN with array: must NOT have a link with value in the array
|
|
750
|
+
const formattedValues = ops.not.map(v => this.formatSurrealValue(v)).join(', ');
|
|
751
|
+
conditions.push(`count(->link[WHERE perspective = $perspective AND predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) = 0`);
|
|
752
|
+
}
|
|
753
|
+
else {
|
|
754
|
+
// For NOT with single value: must NOT have this value
|
|
755
|
+
conditions.push(`count(->link[WHERE perspective = $perspective AND predicate = '${predicate}' AND ${targetField} = ${this.formatSurrealValue(ops.not)}]) = 0`);
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
// Note: gt, gte, lt, lte, between, contains operators are filtered in JavaScript
|
|
759
|
+
// post-query because fn::parse_literal() comparisons in SurrealDB
|
|
760
|
+
// don't work reliably with numeric comparisons.
|
|
761
|
+
// These are handled in instancesFromSurrealResult along with author/timestamp filtering.
|
|
762
|
+
// However, we still need to ensure the property exists
|
|
763
|
+
const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
|
|
764
|
+
ops.lt !== undefined || ops.lte !== undefined ||
|
|
765
|
+
ops.between !== undefined || ops.contains !== undefined;
|
|
766
|
+
if (hasComparisonOps) {
|
|
767
|
+
// Ensure we only get nodes that have this property
|
|
768
|
+
conditions.push(`count(->link[WHERE perspective = $perspective AND predicate = '${predicate}']) > 0`);
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
else {
|
|
772
|
+
// Simple equality
|
|
773
|
+
conditions.push(`count(->link[WHERE perspective = $perspective AND predicate = '${predicate}' AND ${targetField} = ${this.formatSurrealValue(condition)}]) > 0`);
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
return conditions.join(' AND ');
|
|
778
|
+
}
|
|
779
|
+
/**
|
|
780
|
+
* Builds the WHERE clause for SurrealQL queries.
|
|
781
|
+
*
|
|
782
|
+
* @description
|
|
783
|
+
* Translates the where conditions from the Query object into SurrealQL WHERE clause fragments.
|
|
784
|
+
* For each property filter, generates a subquery that checks for links with the appropriate
|
|
785
|
+
* predicate and target value.
|
|
786
|
+
*
|
|
787
|
+
* Handles several condition types:
|
|
788
|
+
* - Simple equality: `{ name: "Pasta" }` → subquery checking for predicate and target match
|
|
789
|
+
* - Arrays (IN clause): `{ name: ["Pasta", "Pizza"] }` → target IN [...]
|
|
790
|
+
* - Operators: `{ rating: { gt: 4 } }` → target > '4'
|
|
791
|
+
* - gt, gte, lt, lte: comparison operators
|
|
792
|
+
* - not: negation (single value or array)
|
|
793
|
+
* - between: range check
|
|
794
|
+
* - contains: substring/element check (uses SurrealQL CONTAINS)
|
|
795
|
+
* - Special fields: base, author, timestamp are accessed directly, not via subqueries
|
|
796
|
+
*
|
|
797
|
+
* All conditions are joined with AND.
|
|
798
|
+
*
|
|
799
|
+
* @param metadata - Model metadata containing property predicates
|
|
800
|
+
* @param where - Where conditions from the query
|
|
801
|
+
* @returns WHERE clause string (without the "WHERE" keyword), or empty string if no conditions
|
|
802
|
+
*
|
|
803
|
+
* @private
|
|
804
|
+
*/
|
|
805
|
+
static buildSurrealWhereClause(metadata, where) {
|
|
806
|
+
if (!where)
|
|
807
|
+
return '';
|
|
808
|
+
const conditions = [];
|
|
809
|
+
for (const [propertyName, condition] of Object.entries(where)) {
|
|
810
|
+
// Check if this is a special field (base, author, timestamp)
|
|
811
|
+
// Note: author and timestamp filtering is done in JavaScript after GROUP BY
|
|
812
|
+
// because they need to be computed from the grouped links first
|
|
813
|
+
const isSpecial = ['base', 'author', 'timestamp'].includes(propertyName);
|
|
814
|
+
if (isSpecial) {
|
|
815
|
+
// Skip author and timestamp - they'll be filtered in JavaScript
|
|
816
|
+
// Only handle 'base' (which maps to 'source') here
|
|
817
|
+
if (propertyName === 'author' || propertyName === 'timestamp') {
|
|
818
|
+
continue; // Skip - will be filtered post-query
|
|
819
|
+
}
|
|
820
|
+
const columnName = 'source'; // base maps to source
|
|
821
|
+
// Handle base/source field directly
|
|
822
|
+
if (Array.isArray(condition)) {
|
|
823
|
+
// Array values (IN clause)
|
|
824
|
+
const formattedValues = condition.map(v => this.formatSurrealValue(v)).join(', ');
|
|
825
|
+
conditions.push(`${columnName} IN [${formattedValues}]`);
|
|
826
|
+
}
|
|
827
|
+
else if (typeof condition === 'object' && condition !== null) {
|
|
828
|
+
// Operator object
|
|
829
|
+
const ops = condition;
|
|
830
|
+
if (ops.not !== undefined) {
|
|
831
|
+
if (Array.isArray(ops.not)) {
|
|
832
|
+
const formattedValues = ops.not.map(v => this.formatSurrealValue(v)).join(', ');
|
|
833
|
+
conditions.push(`${columnName} NOT IN [${formattedValues}]`);
|
|
834
|
+
}
|
|
835
|
+
else {
|
|
836
|
+
conditions.push(`${columnName} != ${this.formatSurrealValue(ops.not)}`);
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
if (ops.between !== undefined && Array.isArray(ops.between) && ops.between.length === 2) {
|
|
840
|
+
conditions.push(`${columnName} >= ${this.formatSurrealValue(ops.between[0])} AND ${columnName} <= ${this.formatSurrealValue(ops.between[1])}`);
|
|
841
|
+
}
|
|
842
|
+
if (ops.gt !== undefined) {
|
|
843
|
+
conditions.push(`${columnName} > ${this.formatSurrealValue(ops.gt)}`);
|
|
844
|
+
}
|
|
845
|
+
if (ops.gte !== undefined) {
|
|
846
|
+
conditions.push(`${columnName} >= ${this.formatSurrealValue(ops.gte)}`);
|
|
847
|
+
}
|
|
848
|
+
if (ops.lt !== undefined) {
|
|
849
|
+
conditions.push(`${columnName} < ${this.formatSurrealValue(ops.lt)}`);
|
|
850
|
+
}
|
|
851
|
+
if (ops.lte !== undefined) {
|
|
852
|
+
conditions.push(`${columnName} <= ${this.formatSurrealValue(ops.lte)}`);
|
|
853
|
+
}
|
|
854
|
+
if (ops.contains !== undefined) {
|
|
855
|
+
conditions.push(`${columnName} CONTAINS ${this.formatSurrealValue(ops.contains)}`);
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
else {
|
|
859
|
+
// Simple equality
|
|
860
|
+
conditions.push(`${columnName} = ${this.formatSurrealValue(condition)}`);
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
else {
|
|
864
|
+
// Handle regular properties via subqueries
|
|
865
|
+
const propMeta = metadata.properties[propertyName];
|
|
866
|
+
if (!propMeta)
|
|
867
|
+
continue; // Skip if property not found in metadata
|
|
868
|
+
const predicate = propMeta.predicate;
|
|
869
|
+
// Use fn::parse_literal() for properties with resolveLanguage
|
|
870
|
+
const targetField = propMeta.resolveLanguage === 'literal' ? 'fn::parse_literal(target)' : 'target';
|
|
871
|
+
if (Array.isArray(condition)) {
|
|
872
|
+
// Array values (IN clause)
|
|
873
|
+
const formattedValues = condition.map(v => this.formatSurrealValue(v)).join(', ');
|
|
874
|
+
conditions.push(`source IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}])`);
|
|
875
|
+
}
|
|
876
|
+
else if (typeof condition === 'object' && condition !== null) {
|
|
877
|
+
// Operator object
|
|
878
|
+
const ops = condition;
|
|
879
|
+
if (ops.not !== undefined) {
|
|
880
|
+
if (Array.isArray(ops.not)) {
|
|
881
|
+
// For NOT IN with array: exclude sources that HAVE a value in the array
|
|
882
|
+
const formattedValues = ops.not.map(v => this.formatSurrealValue(v)).join(', ');
|
|
883
|
+
conditions.push(`source NOT IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}])`);
|
|
884
|
+
}
|
|
885
|
+
else {
|
|
886
|
+
// For NOT with single value: exclude sources that HAVE this value
|
|
887
|
+
conditions.push(`source NOT IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}' AND ${targetField} = ${this.formatSurrealValue(ops.not)})`);
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
// Note: gt, gte, lt, lte, between, contains operators are filtered in JavaScript
|
|
891
|
+
// post-query because fn::parse_literal() comparisons in SurrealDB subqueries
|
|
892
|
+
// don't work reliably with numeric comparisons.
|
|
893
|
+
// These are handled in instancesFromSurrealResult along with author/timestamp filtering.
|
|
894
|
+
// However, we still need to ensure the property exists by filtering on the predicate
|
|
895
|
+
const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
|
|
896
|
+
ops.lt !== undefined || ops.lte !== undefined ||
|
|
897
|
+
ops.between !== undefined || ops.contains !== undefined;
|
|
898
|
+
if (hasComparisonOps) {
|
|
899
|
+
// Ensure we only get instances that have this property
|
|
900
|
+
conditions.push(`source IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}')`);
|
|
901
|
+
}
|
|
902
|
+
}
|
|
903
|
+
else {
|
|
904
|
+
// Simple equality
|
|
905
|
+
conditions.push(`source IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}' AND ${targetField} = ${this.formatSurrealValue(condition)})`);
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
return conditions.join(' AND ');
|
|
910
|
+
}
|
|
911
|
+
/**
|
|
912
|
+
* Builds the SELECT fields for SurrealQL queries.
|
|
913
|
+
*
|
|
914
|
+
* @description
|
|
915
|
+
* Generates the field list for the SELECT clause, resolving properties and collections
|
|
916
|
+
* via subqueries. Each property is fetched with a subquery that finds the link with the
|
|
917
|
+
* appropriate predicate and returns its target. Collections are similar but don't use LIMIT 1.
|
|
918
|
+
*
|
|
919
|
+
* Field types:
|
|
920
|
+
* - Properties: `(SELECT VALUE target FROM link WHERE source = $parent.base AND predicate = 'X' LIMIT 1) AS propName`
|
|
921
|
+
* - Collections: `(SELECT VALUE target FROM link WHERE source = $parent.base AND predicate = 'X') AS collName`
|
|
922
|
+
* - Author/Timestamp: Always included to provide metadata about each instance
|
|
923
|
+
*
|
|
924
|
+
* If properties or collections arrays are provided, only those fields are included.
|
|
925
|
+
* Otherwise, all properties/collections from metadata are included.
|
|
926
|
+
*
|
|
927
|
+
* @param metadata - Model metadata containing property and collection predicates
|
|
928
|
+
* @param properties - Optional array of property names to include (default: all)
|
|
929
|
+
* @param collections - Optional array of collection names to include (default: all)
|
|
930
|
+
* @returns Comma-separated SELECT field list
|
|
931
|
+
*
|
|
932
|
+
* @private
|
|
933
|
+
*/
|
|
934
|
+
static buildSurrealSelectFields(metadata, properties, collections) {
|
|
935
|
+
const fields = [];
|
|
936
|
+
// Determine properties to fetch
|
|
937
|
+
const propsToFetch = properties || Object.keys(metadata.properties);
|
|
938
|
+
for (const propName of propsToFetch) {
|
|
939
|
+
const propMeta = metadata.properties[propName];
|
|
940
|
+
if (!propMeta)
|
|
941
|
+
continue; // Skip if not found
|
|
942
|
+
// Reference source directly since we're selecting from link table
|
|
943
|
+
fields.push(`(SELECT VALUE target FROM link WHERE source = source AND predicate = '${propMeta.predicate}' LIMIT 1) AS ${propName}`);
|
|
944
|
+
}
|
|
945
|
+
// Determine collections to fetch
|
|
946
|
+
const collsToFetch = collections || Object.keys(metadata.collections);
|
|
947
|
+
for (const collName of collsToFetch) {
|
|
948
|
+
const collMeta = metadata.collections[collName];
|
|
949
|
+
if (!collMeta)
|
|
950
|
+
continue; // Skip if not found
|
|
951
|
+
// Reference source directly since we're selecting from link table
|
|
952
|
+
fields.push(`(SELECT VALUE target FROM link WHERE source = source AND predicate = '${collMeta.predicate}') AS ${collName}`);
|
|
953
|
+
}
|
|
954
|
+
// Always add author and timestamp fields
|
|
955
|
+
fields.push(`(SELECT VALUE author FROM link WHERE source = source LIMIT 1) AS author`);
|
|
956
|
+
fields.push(`(SELECT VALUE timestamp FROM link WHERE source = source LIMIT 1) AS timestamp`);
|
|
957
|
+
return fields.join(',\n ');
|
|
958
|
+
}
|
|
959
|
+
/**
|
|
960
|
+
* Builds the SELECT fields for SurrealQL queries using aggregation functions.
|
|
961
|
+
* Compatible with GROUP BY source queries.
|
|
962
|
+
*
|
|
963
|
+
* @private
|
|
964
|
+
*/
|
|
965
|
+
static buildSurrealSelectFieldsWithAggregation(metadata, properties, collections) {
|
|
966
|
+
const fields = [];
|
|
967
|
+
// Determine properties to fetch
|
|
968
|
+
const propsToFetch = properties || Object.keys(metadata.properties);
|
|
969
|
+
for (const propName of propsToFetch) {
|
|
970
|
+
const propMeta = metadata.properties[propName];
|
|
971
|
+
if (!propMeta)
|
|
972
|
+
continue; // Skip if not found
|
|
973
|
+
// Use array::first to get the first target value for this predicate
|
|
974
|
+
fields.push(`array::first(target[WHERE predicate = '${propMeta.predicate}']) AS ${propName}`);
|
|
975
|
+
}
|
|
976
|
+
// Determine collections to fetch
|
|
977
|
+
const collsToFetch = collections || Object.keys(metadata.collections);
|
|
978
|
+
for (const collName of collsToFetch) {
|
|
979
|
+
const collMeta = metadata.collections[collName];
|
|
980
|
+
if (!collMeta)
|
|
981
|
+
continue; // Skip if not found
|
|
982
|
+
// Use array filtering to get all target values for this predicate
|
|
983
|
+
fields.push(`target[WHERE predicate = '${collMeta.predicate}'] AS ${collName}`);
|
|
984
|
+
}
|
|
985
|
+
// Always add author and timestamp fields using array::first
|
|
986
|
+
fields.push(`array::first(author) AS author`);
|
|
987
|
+
fields.push(`array::first(timestamp) AS timestamp`);
|
|
988
|
+
return fields.join(',\n ');
|
|
989
|
+
}
|
|
990
|
+
/**
|
|
991
|
+
* Formats a value for use in SurrealQL queries.
|
|
992
|
+
*
|
|
993
|
+
* @description
|
|
994
|
+
* Handles different value types:
|
|
995
|
+
* - Strings: Wrapped in single quotes with backslash-escaped special characters
|
|
996
|
+
* - Numbers/booleans: Converted to string
|
|
997
|
+
* - Arrays: Recursively formatted and wrapped in brackets
|
|
998
|
+
*
|
|
999
|
+
* @param value - The value to format
|
|
1000
|
+
* @returns Formatted value string ready for SurrealQL
|
|
1001
|
+
*
|
|
1002
|
+
* @private
|
|
1003
|
+
*/
|
|
1004
|
+
static formatSurrealValue(value) {
|
|
1005
|
+
if (typeof value === 'string') {
|
|
1006
|
+
// Escape backslashes first, then single quotes and other special characters
|
|
1007
|
+
const escaped = value
|
|
1008
|
+
.replace(/\\/g, '\\\\') // Backslash -> \\
|
|
1009
|
+
.replace(/'/g, "\\'") // Single quote -> \'
|
|
1010
|
+
.replace(/"/g, '\\"') // Double quote -> \"
|
|
1011
|
+
.replace(/\n/g, '\\n') // Newline -> \n
|
|
1012
|
+
.replace(/\r/g, '\\r') // Carriage return -> \r
|
|
1013
|
+
.replace(/\t/g, '\\t'); // Tab -> \t
|
|
1014
|
+
return `'${escaped}'`;
|
|
1015
|
+
}
|
|
1016
|
+
else if (typeof value === 'number' || typeof value === 'boolean') {
|
|
1017
|
+
return String(value);
|
|
1018
|
+
}
|
|
1019
|
+
else if (Array.isArray(value)) {
|
|
1020
|
+
return `[${value.map(v => this.formatSurrealValue(v)).join(', ')}]`;
|
|
1021
|
+
}
|
|
1022
|
+
else {
|
|
1023
|
+
return String(value);
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
399
1026
|
static async instancesFromPrologResult(perspective, query, result) {
|
|
400
1027
|
if (!result?.[0]?.AllInstances)
|
|
401
1028
|
return { results: [], totalCount: 0 };
|
|
@@ -424,19 +1051,339 @@ export class Ad4mModel {
|
|
|
424
1051
|
}));
|
|
425
1052
|
return { results: allInstances.filter((instance) => instance !== null), totalCount: result[0].TotalCount };
|
|
426
1053
|
}
|
|
1054
|
+
/**
|
|
1055
|
+
* Converts SurrealDB query results to Ad4mModel instances.
|
|
1056
|
+
*
|
|
1057
|
+
* @param perspective - The perspective context
|
|
1058
|
+
* @param query - The query parameters used
|
|
1059
|
+
* @param result - Array of result objects from SurrealDB
|
|
1060
|
+
* @returns Promise resolving to results with total count
|
|
1061
|
+
*
|
|
1062
|
+
* @internal
|
|
1063
|
+
*/
|
|
1064
|
+
static async instancesFromSurrealResult(perspective, query, result) {
|
|
1065
|
+
if (!result || result.length === 0)
|
|
1066
|
+
return { results: [], totalCount: 0 };
|
|
1067
|
+
const metadata = this.getModelMetadata();
|
|
1068
|
+
const requestedProperties = query?.properties || [];
|
|
1069
|
+
const requestedCollections = query?.collections || [];
|
|
1070
|
+
// The query used GROUP BY with graph traversal, so each row has:
|
|
1071
|
+
// - source: the node ID (e.g., "node:abc123")
|
|
1072
|
+
// - source_uri: the actual URI (the base expression)
|
|
1073
|
+
// - links: array of link objects with {predicate, target, author, timestamp}
|
|
1074
|
+
const instances = [];
|
|
1075
|
+
for (const row of result) {
|
|
1076
|
+
let base;
|
|
1077
|
+
try {
|
|
1078
|
+
// Use source_uri as the base (the actual URI), not the node ID
|
|
1079
|
+
base = row.source_uri;
|
|
1080
|
+
// Skip rows without a source_uri field
|
|
1081
|
+
if (!base) {
|
|
1082
|
+
continue;
|
|
1083
|
+
}
|
|
1084
|
+
const links = row.links || [];
|
|
1085
|
+
const instance = new this(perspective, base);
|
|
1086
|
+
// Track the most recent timestamp and corresponding author
|
|
1087
|
+
let maxTimestamp = null;
|
|
1088
|
+
let latestAuthor = null;
|
|
1089
|
+
// Process each link (track index for collection ordering)
|
|
1090
|
+
for (let linkIndex = 0; linkIndex < links.length; linkIndex++) {
|
|
1091
|
+
const link = links[linkIndex];
|
|
1092
|
+
const predicate = link.predicate;
|
|
1093
|
+
const target = link.target;
|
|
1094
|
+
// Skip 'None' values
|
|
1095
|
+
if (target === 'None')
|
|
1096
|
+
continue;
|
|
1097
|
+
// Track the most recent timestamp and its author
|
|
1098
|
+
if (link.timestamp && (!maxTimestamp || link.timestamp > maxTimestamp)) {
|
|
1099
|
+
maxTimestamp = link.timestamp;
|
|
1100
|
+
latestAuthor = link.author;
|
|
1101
|
+
}
|
|
1102
|
+
// Find matching property
|
|
1103
|
+
let foundProperty = false;
|
|
1104
|
+
for (const [propName, propMeta] of Object.entries(metadata.properties)) {
|
|
1105
|
+
if (propMeta.predicate === predicate) {
|
|
1106
|
+
// For properties, take the first value (or we could use timestamp to get latest)
|
|
1107
|
+
// Note: Empty objects {} are truthy, so we need to check for them explicitly
|
|
1108
|
+
const currentValue = instance[propName];
|
|
1109
|
+
const isEmptyObject = typeof currentValue === 'object' && currentValue !== null && !Array.isArray(currentValue) && Object.keys(currentValue).length === 0;
|
|
1110
|
+
if (!currentValue || currentValue === "" || currentValue === 0 || isEmptyObject) {
|
|
1111
|
+
let convertedValue = target;
|
|
1112
|
+
// Parse literal URLs if property has resolveLanguage
|
|
1113
|
+
if (propMeta.resolveLanguage === 'literal' && typeof target === 'string' && target.startsWith('literal://')) {
|
|
1114
|
+
try {
|
|
1115
|
+
convertedValue = Literal.fromUrl(target).get();
|
|
1116
|
+
if (convertedValue.data !== undefined) {
|
|
1117
|
+
convertedValue = convertedValue.data;
|
|
1118
|
+
}
|
|
1119
|
+
}
|
|
1120
|
+
catch (e) {
|
|
1121
|
+
console.warn(`Failed to parse literal URL for ${propName}:`, e);
|
|
1122
|
+
convertedValue = target; // Fall back to raw value
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
else {
|
|
1126
|
+
// Type conversion: check the instance property's current type
|
|
1127
|
+
const expectedType = typeof instance[propName];
|
|
1128
|
+
if (expectedType === 'number' && typeof target === 'string') {
|
|
1129
|
+
convertedValue = Number(target);
|
|
1130
|
+
}
|
|
1131
|
+
else if (expectedType === 'boolean' && typeof target === 'string') {
|
|
1132
|
+
convertedValue = target === 'true' || target === '1';
|
|
1133
|
+
}
|
|
1134
|
+
}
|
|
1135
|
+
// Apply transform function if it exists
|
|
1136
|
+
if (propMeta.transform && typeof propMeta.transform === 'function') {
|
|
1137
|
+
convertedValue = propMeta.transform(convertedValue);
|
|
1138
|
+
}
|
|
1139
|
+
instance[propName] = convertedValue;
|
|
1140
|
+
}
|
|
1141
|
+
foundProperty = true;
|
|
1142
|
+
break;
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1145
|
+
// If not a property, check if it's a collection
|
|
1146
|
+
if (!foundProperty) {
|
|
1147
|
+
for (const [collName, collMeta] of Object.entries(metadata.collections)) {
|
|
1148
|
+
if (collMeta.predicate === predicate) {
|
|
1149
|
+
// For collections, accumulate all values with their timestamps and indices for sorting
|
|
1150
|
+
if (!instance[collName]) {
|
|
1151
|
+
instance[collName] = [];
|
|
1152
|
+
}
|
|
1153
|
+
// Initialize timestamp tracking array if not already done
|
|
1154
|
+
const timestampsKey = `__${collName}_timestamps`;
|
|
1155
|
+
const indicesKey = `__${collName}_indices`;
|
|
1156
|
+
if (!instance[timestampsKey]) {
|
|
1157
|
+
instance[timestampsKey] = [];
|
|
1158
|
+
}
|
|
1159
|
+
if (!instance[indicesKey]) {
|
|
1160
|
+
instance[indicesKey] = [];
|
|
1161
|
+
}
|
|
1162
|
+
if (!instance[collName].includes(target)) {
|
|
1163
|
+
instance[collName].push(target);
|
|
1164
|
+
instance[timestampsKey].push(link.timestamp || '');
|
|
1165
|
+
// Track original position in the links array for stable sorting
|
|
1166
|
+
instance[indicesKey].push(linkIndex);
|
|
1167
|
+
}
|
|
1168
|
+
break;
|
|
1169
|
+
}
|
|
1170
|
+
}
|
|
1171
|
+
}
|
|
1172
|
+
}
|
|
1173
|
+
// Set author and timestamp from the most recent link
|
|
1174
|
+
if (latestAuthor && maxTimestamp) {
|
|
1175
|
+
instance.author = latestAuthor;
|
|
1176
|
+
// Convert timestamp to number (milliseconds) if it's an ISO string
|
|
1177
|
+
if (typeof maxTimestamp === 'string' && maxTimestamp.includes('T')) {
|
|
1178
|
+
instance.timestamp = new Date(maxTimestamp).getTime();
|
|
1179
|
+
}
|
|
1180
|
+
else if (typeof maxTimestamp === 'string') {
|
|
1181
|
+
// Try to parse as number string
|
|
1182
|
+
const parsed = parseInt(maxTimestamp, 10);
|
|
1183
|
+
instance.timestamp = isNaN(parsed) ? maxTimestamp : parsed;
|
|
1184
|
+
}
|
|
1185
|
+
else {
|
|
1186
|
+
instance.timestamp = maxTimestamp;
|
|
1187
|
+
}
|
|
1188
|
+
}
|
|
1189
|
+
// Sort collections by timestamp to maintain insertion order
|
|
1190
|
+
for (const [collName, collMeta] of Object.entries(metadata.collections)) {
|
|
1191
|
+
const timestampsKey = `__${collName}_timestamps`;
|
|
1192
|
+
const indicesKey = `__${collName}_indices`;
|
|
1193
|
+
if (instance[collName] && instance[timestampsKey]) {
|
|
1194
|
+
// Create array of [value, timestamp, index] tuples
|
|
1195
|
+
const pairs = instance[collName].map((value, index) => ({
|
|
1196
|
+
value,
|
|
1197
|
+
timestamp: instance[timestampsKey][index] || '',
|
|
1198
|
+
originalIndex: instance[indicesKey]?.[index] ?? index
|
|
1199
|
+
}));
|
|
1200
|
+
// Sort by timestamp first, then by original index for stable sorting
|
|
1201
|
+
pairs.sort((a, b) => {
|
|
1202
|
+
const tsA = String(a.timestamp || '');
|
|
1203
|
+
const tsB = String(b.timestamp || '');
|
|
1204
|
+
const tsCompare = tsA.localeCompare(tsB);
|
|
1205
|
+
if (tsCompare !== 0)
|
|
1206
|
+
return tsCompare;
|
|
1207
|
+
// Use original index as tiebreaker for stable sorting
|
|
1208
|
+
return a.originalIndex - b.originalIndex;
|
|
1209
|
+
});
|
|
1210
|
+
// Replace collection with sorted values
|
|
1211
|
+
instance[collName] = pairs.map(p => p.value);
|
|
1212
|
+
// Clean up temporary arrays
|
|
1213
|
+
delete instance[timestampsKey];
|
|
1214
|
+
delete instance[indicesKey];
|
|
1215
|
+
}
|
|
1216
|
+
}
|
|
1217
|
+
// Filter by requested attributes if specified
|
|
1218
|
+
if (requestedProperties.length > 0 || requestedCollections.length > 0) {
|
|
1219
|
+
const requestedAttributes = [...requestedProperties, ...requestedCollections];
|
|
1220
|
+
Object.keys(instance).forEach((key) => {
|
|
1221
|
+
// Keep only requested attributes, plus always keep timestamp and author
|
|
1222
|
+
if (!requestedAttributes.includes(key) && key !== 'timestamp' && key !== 'author' && key !== 'baseExpression') {
|
|
1223
|
+
delete instance[key];
|
|
1224
|
+
}
|
|
1225
|
+
});
|
|
1226
|
+
}
|
|
1227
|
+
instances.push(instance);
|
|
1228
|
+
}
|
|
1229
|
+
catch (error) {
|
|
1230
|
+
console.error(`Failed to process SurrealDB instance ${base}:`, error);
|
|
1231
|
+
}
|
|
1232
|
+
}
|
|
1233
|
+
// Filter by where conditions that couldn't be filtered in SQL
|
|
1234
|
+
// This includes:
|
|
1235
|
+
// - author/timestamp (computed from grouped links)
|
|
1236
|
+
// - Properties with comparison operators (gt, gte, lt, lte, between, contains)
|
|
1237
|
+
// because fn::parse_literal() comparisons in SurrealDB subqueries don't work reliably
|
|
1238
|
+
let filteredInstances = instances;
|
|
1239
|
+
if (query.where) {
|
|
1240
|
+
filteredInstances = instances.filter(instance => {
|
|
1241
|
+
for (const [propertyName, condition] of Object.entries(query.where)) {
|
|
1242
|
+
// Skip 'base' as it's filtered in SQL
|
|
1243
|
+
if (propertyName === 'base')
|
|
1244
|
+
continue;
|
|
1245
|
+
// For author and timestamp, always filter in JS
|
|
1246
|
+
if (propertyName === 'author' || propertyName === 'timestamp') {
|
|
1247
|
+
if (!this.matchesCondition(instance[propertyName], condition)) {
|
|
1248
|
+
return false;
|
|
1249
|
+
}
|
|
1250
|
+
continue;
|
|
1251
|
+
}
|
|
1252
|
+
// For regular properties, only filter comparison operators in JS
|
|
1253
|
+
// Simple equality and NOT are handled in SQL, but gt/gte/lt/lte/between/contains need JS
|
|
1254
|
+
if (typeof condition === 'object' && condition !== null && !Array.isArray(condition)) {
|
|
1255
|
+
const ops = condition;
|
|
1256
|
+
// Check if any comparison operators are present
|
|
1257
|
+
const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
|
|
1258
|
+
ops.lt !== undefined || ops.lte !== undefined ||
|
|
1259
|
+
ops.between !== undefined || ops.contains !== undefined;
|
|
1260
|
+
if (hasComparisonOps) {
|
|
1261
|
+
if (!this.matchesCondition(instance[propertyName], condition)) {
|
|
1262
|
+
return false;
|
|
1263
|
+
}
|
|
1264
|
+
}
|
|
1265
|
+
}
|
|
1266
|
+
}
|
|
1267
|
+
return true;
|
|
1268
|
+
});
|
|
1269
|
+
}
|
|
1270
|
+
// Apply ordering in JavaScript
|
|
1271
|
+
// If limit/offset is used but no explicit order, default to ordering by timestamp (ASC)
|
|
1272
|
+
// This ensures consistent pagination behavior
|
|
1273
|
+
const effectiveOrder = query.order ||
|
|
1274
|
+
(query.limit !== undefined || query.offset !== undefined ? { timestamp: 'ASC' } : null);
|
|
1275
|
+
if (effectiveOrder) {
|
|
1276
|
+
const orderPropName = Object.keys(effectiveOrder)[0];
|
|
1277
|
+
const orderDirection = Object.values(effectiveOrder)[0];
|
|
1278
|
+
filteredInstances.sort((a, b) => {
|
|
1279
|
+
let aVal = a[orderPropName];
|
|
1280
|
+
let bVal = b[orderPropName];
|
|
1281
|
+
// Handle undefined values - push them to the end
|
|
1282
|
+
if (aVal === undefined && bVal === undefined)
|
|
1283
|
+
return 0;
|
|
1284
|
+
if (aVal === undefined)
|
|
1285
|
+
return orderDirection === 'ASC' ? 1 : -1;
|
|
1286
|
+
if (bVal === undefined)
|
|
1287
|
+
return orderDirection === 'ASC' ? -1 : 1;
|
|
1288
|
+
// Compare values
|
|
1289
|
+
let comparison = 0;
|
|
1290
|
+
if (typeof aVal === 'number' && typeof bVal === 'number') {
|
|
1291
|
+
comparison = aVal - bVal;
|
|
1292
|
+
}
|
|
1293
|
+
else if (typeof aVal === 'string' && typeof bVal === 'string') {
|
|
1294
|
+
comparison = aVal.localeCompare(bVal);
|
|
1295
|
+
}
|
|
1296
|
+
else {
|
|
1297
|
+
// Convert to strings for comparison
|
|
1298
|
+
comparison = String(aVal).localeCompare(String(bVal));
|
|
1299
|
+
}
|
|
1300
|
+
return orderDirection === 'DESC' ? -comparison : comparison;
|
|
1301
|
+
});
|
|
1302
|
+
}
|
|
1303
|
+
// Calculate totalCount BEFORE applying limit/offset
|
|
1304
|
+
const totalCount = filteredInstances.length;
|
|
1305
|
+
// Apply offset and limit in JavaScript
|
|
1306
|
+
let paginatedInstances = filteredInstances;
|
|
1307
|
+
if (query.offset !== undefined || query.limit !== undefined) {
|
|
1308
|
+
const start = query.offset || 0;
|
|
1309
|
+
const end = query.limit ? start + query.limit : undefined;
|
|
1310
|
+
paginatedInstances = filteredInstances.slice(start, end);
|
|
1311
|
+
}
|
|
1312
|
+
return {
|
|
1313
|
+
results: paginatedInstances,
|
|
1314
|
+
totalCount
|
|
1315
|
+
};
|
|
1316
|
+
}
|
|
1317
|
+
/**
|
|
1318
|
+
* Checks if a value matches a condition (for post-query filtering).
|
|
1319
|
+
* @private
|
|
1320
|
+
*/
|
|
1321
|
+
static matchesCondition(value, condition) {
|
|
1322
|
+
// Handle array values (IN clause)
|
|
1323
|
+
if (Array.isArray(condition)) {
|
|
1324
|
+
return condition.includes(value);
|
|
1325
|
+
}
|
|
1326
|
+
// Handle operator object
|
|
1327
|
+
if (typeof condition === 'object' && condition !== null) {
|
|
1328
|
+
const ops = condition;
|
|
1329
|
+
// Special case: 'not' operator (exclusive with other operators)
|
|
1330
|
+
if (ops.not !== undefined) {
|
|
1331
|
+
if (Array.isArray(ops.not)) {
|
|
1332
|
+
return !ops.not.includes(value);
|
|
1333
|
+
}
|
|
1334
|
+
else {
|
|
1335
|
+
return value !== ops.not;
|
|
1336
|
+
}
|
|
1337
|
+
}
|
|
1338
|
+
// Special case: 'between' operator (inclusive range, exclusive with gt/gte/lt/lte)
|
|
1339
|
+
if (ops.between !== undefined && Array.isArray(ops.between) && ops.between.length === 2) {
|
|
1340
|
+
return value >= ops.between[0] && value <= ops.between[1];
|
|
1341
|
+
}
|
|
1342
|
+
// For all other operators (gt, gte, lt, lte, contains), we need to check ALL of them
|
|
1343
|
+
// and return true only if ALL conditions are satisfied
|
|
1344
|
+
let allConditionsMet = true;
|
|
1345
|
+
if (ops.gt !== undefined) {
|
|
1346
|
+
allConditionsMet = allConditionsMet && (value > ops.gt);
|
|
1347
|
+
}
|
|
1348
|
+
if (ops.gte !== undefined) {
|
|
1349
|
+
allConditionsMet = allConditionsMet && (value >= ops.gte);
|
|
1350
|
+
}
|
|
1351
|
+
if (ops.lt !== undefined) {
|
|
1352
|
+
allConditionsMet = allConditionsMet && (value < ops.lt);
|
|
1353
|
+
}
|
|
1354
|
+
if (ops.lte !== undefined) {
|
|
1355
|
+
allConditionsMet = allConditionsMet && (value <= ops.lte);
|
|
1356
|
+
}
|
|
1357
|
+
if (ops.contains !== undefined) {
|
|
1358
|
+
if (typeof value === 'string') {
|
|
1359
|
+
allConditionsMet = allConditionsMet && value.includes(String(ops.contains));
|
|
1360
|
+
}
|
|
1361
|
+
else if (Array.isArray(value)) {
|
|
1362
|
+
allConditionsMet = allConditionsMet && value.includes(ops.contains);
|
|
1363
|
+
}
|
|
1364
|
+
else {
|
|
1365
|
+
allConditionsMet = false;
|
|
1366
|
+
}
|
|
1367
|
+
}
|
|
1368
|
+
return allConditionsMet;
|
|
1369
|
+
}
|
|
1370
|
+
// Simple equality
|
|
1371
|
+
return value === condition;
|
|
1372
|
+
}
|
|
427
1373
|
/**
|
|
428
1374
|
* Gets all instances of the model in the perspective that match the query params.
|
|
429
1375
|
*
|
|
430
1376
|
* @param perspective - The perspective to search in
|
|
431
1377
|
* @param query - Optional query parameters to filter results
|
|
1378
|
+
* @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
|
|
432
1379
|
* @returns Array of matching models
|
|
433
1380
|
*
|
|
434
1381
|
* @example
|
|
435
1382
|
* ```typescript
|
|
436
|
-
* // Get all recipes
|
|
1383
|
+
* // Get all recipes (uses SurrealDB by default)
|
|
437
1384
|
* const allRecipes = await Recipe.findAll(perspective);
|
|
438
1385
|
*
|
|
439
|
-
* // Get recipes with specific criteria
|
|
1386
|
+
* // Get recipes with specific criteria (uses SurrealDB)
|
|
440
1387
|
* const recipes = await Recipe.findAll(perspective, {
|
|
441
1388
|
* where: {
|
|
442
1389
|
* name: "Pasta",
|
|
@@ -445,19 +1392,31 @@ export class Ad4mModel {
|
|
|
445
1392
|
* order: { createdAt: "DESC" },
|
|
446
1393
|
* limit: 10
|
|
447
1394
|
* });
|
|
1395
|
+
*
|
|
1396
|
+
* // Explicitly use Prolog (legacy, for backward compatibility)
|
|
1397
|
+
* const recipesProlog = await Recipe.findAll(perspective, {}, false);
|
|
448
1398
|
* ```
|
|
449
1399
|
*/
|
|
450
|
-
static async findAll(perspective, query = {}) {
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
1400
|
+
static async findAll(perspective, query = {}, useSurrealDB = true) {
|
|
1401
|
+
if (useSurrealDB) {
|
|
1402
|
+
const surrealQuery = await this.queryToSurrealQL(perspective, query);
|
|
1403
|
+
const result = await perspective.querySurrealDB(surrealQuery);
|
|
1404
|
+
const { results } = await this.instancesFromSurrealResult(perspective, query, result);
|
|
1405
|
+
return results;
|
|
1406
|
+
}
|
|
1407
|
+
else {
|
|
1408
|
+
const prologQuery = await this.queryToProlog(perspective, query);
|
|
1409
|
+
const result = await perspective.infer(prologQuery);
|
|
1410
|
+
const { results } = await this.instancesFromPrologResult(perspective, query, result);
|
|
1411
|
+
return results;
|
|
1412
|
+
}
|
|
455
1413
|
}
|
|
456
1414
|
/**
|
|
457
1415
|
* Gets all instances with count of total matches without offset & limit applied.
|
|
458
1416
|
*
|
|
459
1417
|
* @param perspective - The perspective to search in
|
|
460
1418
|
* @param query - Optional query parameters to filter results
|
|
1419
|
+
* @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
|
|
461
1420
|
* @returns Object containing results array and total count
|
|
462
1421
|
*
|
|
463
1422
|
* @example
|
|
@@ -467,12 +1426,22 @@ export class Ad4mModel {
|
|
|
467
1426
|
* limit: 10
|
|
468
1427
|
* });
|
|
469
1428
|
* console.log(`Showing 10 of ${totalCount} dessert recipes`);
|
|
1429
|
+
*
|
|
1430
|
+
* // Use Prolog explicitly (legacy)
|
|
1431
|
+
* const { results, totalCount } = await Recipe.findAllAndCount(perspective, {}, false);
|
|
470
1432
|
* ```
|
|
471
1433
|
*/
|
|
472
|
-
static async findAllAndCount(perspective, query = {}) {
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
1434
|
+
static async findAllAndCount(perspective, query = {}, useSurrealDB = true) {
|
|
1435
|
+
if (useSurrealDB) {
|
|
1436
|
+
const surrealQuery = await this.queryToSurrealQL(perspective, query);
|
|
1437
|
+
const result = await perspective.querySurrealDB(surrealQuery);
|
|
1438
|
+
return await this.instancesFromSurrealResult(perspective, query, result);
|
|
1439
|
+
}
|
|
1440
|
+
else {
|
|
1441
|
+
const prologQuery = await this.queryToProlog(perspective, query);
|
|
1442
|
+
const result = await perspective.infer(prologQuery);
|
|
1443
|
+
return await this.instancesFromPrologResult(perspective, query, result);
|
|
1444
|
+
}
|
|
476
1445
|
}
|
|
477
1446
|
/**
|
|
478
1447
|
* Helper function for pagination with explicit page size and number.
|
|
@@ -481,6 +1450,7 @@ export class Ad4mModel {
|
|
|
481
1450
|
* @param pageSize - Number of items per page
|
|
482
1451
|
* @param pageNumber - Which page to retrieve (1-based)
|
|
483
1452
|
* @param query - Optional additional query parameters
|
|
1453
|
+
* @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
|
|
484
1454
|
* @returns Paginated results with metadata
|
|
485
1455
|
*
|
|
486
1456
|
* @example
|
|
@@ -489,14 +1459,25 @@ export class Ad4mModel {
|
|
|
489
1459
|
* where: { category: "Main Course" }
|
|
490
1460
|
* });
|
|
491
1461
|
* console.log(`Page ${page.pageNumber} of recipes, ${page.results.length} items`);
|
|
1462
|
+
*
|
|
1463
|
+
* // Use Prolog explicitly (legacy)
|
|
1464
|
+
* const pageProlog = await Recipe.paginate(perspective, 10, 1, {}, false);
|
|
492
1465
|
* ```
|
|
493
1466
|
*/
|
|
494
|
-
static async paginate(perspective, pageSize, pageNumber, query) {
|
|
1467
|
+
static async paginate(perspective, pageSize, pageNumber, query, useSurrealDB = true) {
|
|
495
1468
|
const paginationQuery = { ...(query || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
1469
|
+
if (useSurrealDB) {
|
|
1470
|
+
const surrealQuery = await this.queryToSurrealQL(perspective, paginationQuery);
|
|
1471
|
+
const result = await perspective.querySurrealDB(surrealQuery);
|
|
1472
|
+
const { results, totalCount } = await this.instancesFromSurrealResult(perspective, paginationQuery, result);
|
|
1473
|
+
return { results, totalCount, pageSize, pageNumber };
|
|
1474
|
+
}
|
|
1475
|
+
else {
|
|
1476
|
+
const prologQuery = await this.queryToProlog(perspective, paginationQuery);
|
|
1477
|
+
const result = await perspective.infer(prologQuery);
|
|
1478
|
+
const { results, totalCount } = await this.instancesFromPrologResult(perspective, paginationQuery, result);
|
|
1479
|
+
return { results, totalCount, pageSize, pageNumber };
|
|
1480
|
+
}
|
|
500
1481
|
}
|
|
501
1482
|
static async countQueryToProlog(perspective, query = {}, modelClassName) {
|
|
502
1483
|
const { source, where } = query;
|
|
@@ -513,11 +1494,29 @@ export class Ad4mModel {
|
|
|
513
1494
|
`;
|
|
514
1495
|
return fullQuery;
|
|
515
1496
|
}
|
|
1497
|
+
/**
|
|
1498
|
+
* Generates a SurrealQL COUNT query for the model.
|
|
1499
|
+
*
|
|
1500
|
+
* @param perspective - The perspective context
|
|
1501
|
+
* @param query - Query parameters to filter the count
|
|
1502
|
+
* @returns SurrealQL COUNT query string
|
|
1503
|
+
*
|
|
1504
|
+
* @private
|
|
1505
|
+
*/
|
|
1506
|
+
static async countQueryToSurrealQL(perspective, query) {
|
|
1507
|
+
// Use the same query as the main query (with GROUP BY), just without LIMIT/OFFSET
|
|
1508
|
+
// We'll count the number of rows returned (one row per source)
|
|
1509
|
+
const countQuery = { ...query };
|
|
1510
|
+
delete countQuery.limit;
|
|
1511
|
+
delete countQuery.offset;
|
|
1512
|
+
return await this.queryToSurrealQL(perspective, countQuery);
|
|
1513
|
+
}
|
|
516
1514
|
/**
|
|
517
1515
|
* Gets a count of all matching instances.
|
|
518
1516
|
*
|
|
519
1517
|
* @param perspective - The perspective to search in
|
|
520
1518
|
* @param query - Optional query parameters to filter results
|
|
1519
|
+
* @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
|
|
521
1520
|
* @returns Total count of matching entities
|
|
522
1521
|
*
|
|
523
1522
|
* @example
|
|
@@ -526,11 +1525,25 @@ export class Ad4mModel {
|
|
|
526
1525
|
* const activeRecipes = await Recipe.count(perspective, {
|
|
527
1526
|
* where: { status: "active" }
|
|
528
1527
|
* });
|
|
1528
|
+
*
|
|
1529
|
+
* // Use Prolog explicitly (legacy)
|
|
1530
|
+
* const countProlog = await Recipe.count(perspective, {}, false);
|
|
529
1531
|
* ```
|
|
530
1532
|
*/
|
|
531
|
-
static async count(perspective, query = {}) {
|
|
532
|
-
|
|
533
|
-
|
|
1533
|
+
static async count(perspective, query = {}, useSurrealDB = true) {
|
|
1534
|
+
if (useSurrealDB) {
|
|
1535
|
+
const surrealQuery = await this.queryToSurrealQL(perspective, query);
|
|
1536
|
+
const result = await perspective.querySurrealDB(surrealQuery);
|
|
1537
|
+
// Use instancesFromSurrealResult to apply JS-level filtering for advanced where conditions
|
|
1538
|
+
// (e.g., gt, gte, lt, lte, between, contains on properties and author/timestamp)
|
|
1539
|
+
// This ensures count() returns the same number as findAll().length
|
|
1540
|
+
const { totalCount } = await this.instancesFromSurrealResult(perspective, query, result);
|
|
1541
|
+
return totalCount;
|
|
1542
|
+
}
|
|
1543
|
+
else {
|
|
1544
|
+
const result = await perspective.infer(await this.countQueryToProlog(perspective, query));
|
|
1545
|
+
return result?.[0]?.TotalCount || 0;
|
|
1546
|
+
}
|
|
534
1547
|
}
|
|
535
1548
|
async setProperty(key, value, batchId) {
|
|
536
1549
|
const setters = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _Ad4mModel_subjectClassName, "f")}", C), property_setter(C, "${key}", Setter)`);
|
|
@@ -772,6 +1785,318 @@ export class Ad4mModel {
|
|
|
772
1785
|
static query(perspective, query) {
|
|
773
1786
|
return new ModelQueryBuilder(perspective, this, query);
|
|
774
1787
|
}
|
|
1788
|
+
/**
|
|
1789
|
+
* Creates an Ad4mModel class from a JSON Schema definition.
|
|
1790
|
+
*
|
|
1791
|
+
* @description
|
|
1792
|
+
* This method dynamically generates an Ad4mModel subclass from a JSON Schema,
|
|
1793
|
+
* enabling integration with systems that use JSON Schema for type definitions.
|
|
1794
|
+
*
|
|
1795
|
+
* The method follows a cascading approach for determining predicates:
|
|
1796
|
+
* 1. Explicit configuration in options parameter (highest precedence)
|
|
1797
|
+
* 2. x-ad4m metadata in the JSON Schema
|
|
1798
|
+
* 3. Inference from schema title and property names
|
|
1799
|
+
* 4. Error if no namespace can be determined
|
|
1800
|
+
*
|
|
1801
|
+
* @example
|
|
1802
|
+
* ```typescript
|
|
1803
|
+
* // With explicit configuration
|
|
1804
|
+
* const PersonClass = Ad4mModel.fromJSONSchema(schema, {
|
|
1805
|
+
* name: "Person",
|
|
1806
|
+
* namespace: "person://",
|
|
1807
|
+
* resolveLanguage: "literal"
|
|
1808
|
+
* });
|
|
1809
|
+
*
|
|
1810
|
+
* // With property mapping
|
|
1811
|
+
* const ContactClass = Ad4mModel.fromJSONSchema(schema, {
|
|
1812
|
+
* name: "Contact",
|
|
1813
|
+
* namespace: "contact://",
|
|
1814
|
+
* propertyMapping: {
|
|
1815
|
+
* "name": "foaf://name",
|
|
1816
|
+
* "email": "foaf://mbox"
|
|
1817
|
+
* }
|
|
1818
|
+
* });
|
|
1819
|
+
*
|
|
1820
|
+
* // With x-ad4m metadata in schema
|
|
1821
|
+
* const schema = {
|
|
1822
|
+
* "title": "Product",
|
|
1823
|
+
* "x-ad4m": { "namespace": "product://" },
|
|
1824
|
+
* "properties": {
|
|
1825
|
+
* "name": {
|
|
1826
|
+
* "type": "string",
|
|
1827
|
+
* "x-ad4m": { "through": "product://title" }
|
|
1828
|
+
* }
|
|
1829
|
+
* }
|
|
1830
|
+
* };
|
|
1831
|
+
* const ProductClass = Ad4mModel.fromJSONSchema(schema, { name: "Product" });
|
|
1832
|
+
* ```
|
|
1833
|
+
*
|
|
1834
|
+
* @param schema - JSON Schema definition
|
|
1835
|
+
* @param options - Configuration options
|
|
1836
|
+
* @returns Generated Ad4mModel subclass
|
|
1837
|
+
* @throws Error when namespace cannot be inferred
|
|
1838
|
+
*/
|
|
1839
|
+
static fromJSONSchema(schema, options) {
|
|
1840
|
+
// Disallow top-level "author" property since Ad4mModel provides it implicitly via link authorship
|
|
1841
|
+
if (schema?.properties && Object.prototype.hasOwnProperty.call(schema.properties, "author")) {
|
|
1842
|
+
throw new Error('JSON Schema must not define a top-level "author" property because Ad4mModel already exposes it. Please rename the property (e.g., "writer").');
|
|
1843
|
+
}
|
|
1844
|
+
// Determine namespace with cascading precedence
|
|
1845
|
+
const namespace = this.determineNamespace(schema, options);
|
|
1846
|
+
// Create the dynamic class
|
|
1847
|
+
const DynamicModelClass = class extends Ad4mModel {
|
|
1848
|
+
};
|
|
1849
|
+
// Set up class metadata
|
|
1850
|
+
if (!options.name || options.name.trim() === '') {
|
|
1851
|
+
throw new Error("options.name is required and cannot be empty");
|
|
1852
|
+
}
|
|
1853
|
+
DynamicModelClass.className = options.name;
|
|
1854
|
+
DynamicModelClass.prototype.className = options.name;
|
|
1855
|
+
// Generate properties and collections metadata
|
|
1856
|
+
const properties = {};
|
|
1857
|
+
const collections = {};
|
|
1858
|
+
if (schema.properties) {
|
|
1859
|
+
for (const [propertyName, propertySchema] of Object.entries(schema.properties)) {
|
|
1860
|
+
const predicate = this.determinePredicate(schema, propertyName, propertySchema, namespace, options);
|
|
1861
|
+
const isRequired = schema.required?.includes(propertyName) || false;
|
|
1862
|
+
const propertyType = normalizeSchemaType(propertySchema.type);
|
|
1863
|
+
const isArray = isArrayType(propertySchema);
|
|
1864
|
+
if (isArray) {
|
|
1865
|
+
// Handle arrays as collections
|
|
1866
|
+
// Store the singular form as the collection key since SDNA generation expects singular
|
|
1867
|
+
collections[propertyName] = {
|
|
1868
|
+
through: predicate,
|
|
1869
|
+
local: this.getPropertyOption(propertyName, propertySchema, options, 'local')
|
|
1870
|
+
};
|
|
1871
|
+
// Define the property on prototype
|
|
1872
|
+
Object.defineProperty(DynamicModelClass.prototype, propertyName, {
|
|
1873
|
+
configurable: true,
|
|
1874
|
+
writable: true,
|
|
1875
|
+
value: []
|
|
1876
|
+
});
|
|
1877
|
+
// Add collection methods
|
|
1878
|
+
const adderName = `add${capitalize(propertyName)}`;
|
|
1879
|
+
const removerName = `remove${capitalize(propertyName)}`;
|
|
1880
|
+
const setterName = `setCollection${capitalize(propertyName)}`;
|
|
1881
|
+
DynamicModelClass.prototype[adderName] = function () {
|
|
1882
|
+
// Placeholder function for SDNA generation
|
|
1883
|
+
};
|
|
1884
|
+
DynamicModelClass.prototype[removerName] = function () {
|
|
1885
|
+
// Placeholder function for SDNA generation
|
|
1886
|
+
};
|
|
1887
|
+
DynamicModelClass.prototype[setterName] = function () {
|
|
1888
|
+
// Placeholder function for SDNA generation
|
|
1889
|
+
};
|
|
1890
|
+
}
|
|
1891
|
+
else {
|
|
1892
|
+
// Handle regular properties
|
|
1893
|
+
let resolveLanguage = this.getPropertyOption(propertyName, propertySchema, options, 'resolveLanguage');
|
|
1894
|
+
// If no specific resolveLanguage for this property, use the global one
|
|
1895
|
+
if (!resolveLanguage && options.resolveLanguage) {
|
|
1896
|
+
resolveLanguage = options.resolveLanguage;
|
|
1897
|
+
}
|
|
1898
|
+
const local = this.getPropertyOption(propertyName, propertySchema, options, 'local');
|
|
1899
|
+
const writable = this.getPropertyOption(propertyName, propertySchema, options, 'writable', true);
|
|
1900
|
+
let initial = this.getPropertyOption(propertyName, propertySchema, options, 'initial');
|
|
1901
|
+
// Handle nested objects by serializing to JSON
|
|
1902
|
+
if (isObjectType(propertySchema) && !resolveLanguage) {
|
|
1903
|
+
resolveLanguage = 'literal';
|
|
1904
|
+
console.warn(`Property "${propertyName}" is an object type. It will be stored as JSON. Consider flattening complex objects for better semantic querying.`);
|
|
1905
|
+
}
|
|
1906
|
+
// Ensure numeric properties use literal language for correct typing
|
|
1907
|
+
if ((resolveLanguage === undefined || resolveLanguage === null) && isNumericType(propertySchema)) {
|
|
1908
|
+
resolveLanguage = 'literal';
|
|
1909
|
+
}
|
|
1910
|
+
// If property is required, ensure it has an initial value
|
|
1911
|
+
if (isRequired && !initial) {
|
|
1912
|
+
if (isObjectType(propertySchema)) {
|
|
1913
|
+
initial = 'literal://json:{}';
|
|
1914
|
+
}
|
|
1915
|
+
else {
|
|
1916
|
+
initial = "ad4m://undefined";
|
|
1917
|
+
}
|
|
1918
|
+
}
|
|
1919
|
+
properties[propertyName] = {
|
|
1920
|
+
through: predicate,
|
|
1921
|
+
required: isRequired,
|
|
1922
|
+
writable: writable,
|
|
1923
|
+
...(resolveLanguage && { resolveLanguage }),
|
|
1924
|
+
...(local !== undefined && { local }),
|
|
1925
|
+
...(initial && { initial })
|
|
1926
|
+
};
|
|
1927
|
+
// Define the property on prototype
|
|
1928
|
+
Object.defineProperty(DynamicModelClass.prototype, propertyName, {
|
|
1929
|
+
configurable: true,
|
|
1930
|
+
writable: true,
|
|
1931
|
+
value: this.getDefaultValueForType(propertyType)
|
|
1932
|
+
});
|
|
1933
|
+
// Add setter function if writable
|
|
1934
|
+
if (writable) {
|
|
1935
|
+
const setterName = propertyNameToSetterName(propertyName);
|
|
1936
|
+
DynamicModelClass.prototype[setterName] = function () {
|
|
1937
|
+
// This is a placeholder function that the SDNA generation looks for
|
|
1938
|
+
// The actual setter logic is handled by the Ad4mModel base class
|
|
1939
|
+
};
|
|
1940
|
+
}
|
|
1941
|
+
}
|
|
1942
|
+
}
|
|
1943
|
+
}
|
|
1944
|
+
// Validate that at least one property has an initial value (needed for valid SDNA constructor)
|
|
1945
|
+
// Collections don't create constructor actions, only properties with initial values do
|
|
1946
|
+
const hasPropertyWithInitial = Object.values(properties).some((prop) => prop.initial);
|
|
1947
|
+
if (!hasPropertyWithInitial) {
|
|
1948
|
+
// If no properties have initial values, add a type identifier automatically
|
|
1949
|
+
const typeProperty = `ad4m://type`;
|
|
1950
|
+
let typeValue;
|
|
1951
|
+
if (namespace.includes('://')) {
|
|
1952
|
+
const [scheme, rest] = namespace.split('://');
|
|
1953
|
+
const path = (rest || '').replace(/\/+$/, '');
|
|
1954
|
+
if (path) {
|
|
1955
|
+
typeValue = `${scheme}://${path}/instance`;
|
|
1956
|
+
}
|
|
1957
|
+
else {
|
|
1958
|
+
typeValue = `${scheme}://instance`;
|
|
1959
|
+
}
|
|
1960
|
+
}
|
|
1961
|
+
else {
|
|
1962
|
+
const path = namespace.replace(/\/+$/, '');
|
|
1963
|
+
typeValue = `${path}/instance`;
|
|
1964
|
+
}
|
|
1965
|
+
properties['__ad4m_type'] = {
|
|
1966
|
+
through: typeProperty,
|
|
1967
|
+
required: true,
|
|
1968
|
+
writable: false,
|
|
1969
|
+
initial: typeValue,
|
|
1970
|
+
flag: true
|
|
1971
|
+
};
|
|
1972
|
+
// Add the type property to the prototype
|
|
1973
|
+
Object.defineProperty(DynamicModelClass.prototype, '__ad4m_type', {
|
|
1974
|
+
configurable: true,
|
|
1975
|
+
writable: false,
|
|
1976
|
+
value: typeValue
|
|
1977
|
+
});
|
|
1978
|
+
console.warn(`No properties with initial values found. Added automatic type flag: ${typeProperty} = ${typeValue}`);
|
|
1979
|
+
}
|
|
1980
|
+
// Attach metadata to prototype
|
|
1981
|
+
DynamicModelClass.prototype.__properties = properties;
|
|
1982
|
+
DynamicModelClass.prototype.__collections = collections;
|
|
1983
|
+
// Store the JSON schema and options on the prototype for potential fallback use by getModelMetadata()
|
|
1984
|
+
DynamicModelClass.prototype.__jsonSchema = schema;
|
|
1985
|
+
DynamicModelClass.prototype.__jsonSchemaOptions = options;
|
|
1986
|
+
// Apply the ModelOptions decorator to set up the generateSDNA method
|
|
1987
|
+
const ModelOptionsDecorator = ModelOptions({ name: options.name });
|
|
1988
|
+
ModelOptionsDecorator(DynamicModelClass);
|
|
1989
|
+
return DynamicModelClass;
|
|
1990
|
+
}
|
|
1991
|
+
/**
|
|
1992
|
+
* Determines the namespace for predicates using cascading precedence
|
|
1993
|
+
*/
|
|
1994
|
+
static determineNamespace(schema, options) {
|
|
1995
|
+
// 1. Explicit namespace in options (highest precedence)
|
|
1996
|
+
if (options.namespace) {
|
|
1997
|
+
return options.namespace;
|
|
1998
|
+
}
|
|
1999
|
+
// 2. x-ad4m metadata in schema
|
|
2000
|
+
if (schema["x-ad4m"]?.namespace) {
|
|
2001
|
+
return schema["x-ad4m"].namespace;
|
|
2002
|
+
}
|
|
2003
|
+
// 3. Infer from schema title
|
|
2004
|
+
if (schema.title) {
|
|
2005
|
+
return `${schema.title.toLowerCase()}://`;
|
|
2006
|
+
}
|
|
2007
|
+
// 4. Try to extract from $id if it's a URL
|
|
2008
|
+
if (schema.$id) {
|
|
2009
|
+
try {
|
|
2010
|
+
const url = new URL(schema.$id);
|
|
2011
|
+
const pathParts = url.pathname.split('/').filter(p => p);
|
|
2012
|
+
if (pathParts.length > 0) {
|
|
2013
|
+
const lastPart = pathParts[pathParts.length - 1];
|
|
2014
|
+
const baseName = lastPart.replace(/\.schema\.json$/, '').replace(/\.json$/, '');
|
|
2015
|
+
return `${baseName.toLowerCase()}://`;
|
|
2016
|
+
}
|
|
2017
|
+
}
|
|
2018
|
+
catch {
|
|
2019
|
+
// If $id is not a valid URL, continue to error
|
|
2020
|
+
}
|
|
2021
|
+
}
|
|
2022
|
+
// 5. Error if no namespace can be determined
|
|
2023
|
+
throw new Error(`Cannot infer namespace for JSON Schema. Please provide one of:
|
|
2024
|
+
- options.namespace
|
|
2025
|
+
- schema["x-ad4m"].namespace
|
|
2026
|
+
- schema.title
|
|
2027
|
+
- valid schema.$id`);
|
|
2028
|
+
}
|
|
2029
|
+
/**
|
|
2030
|
+
* Determines the predicate for a specific property using cascading precedence
|
|
2031
|
+
*/
|
|
2032
|
+
static determinePredicate(schema, propertyName, propertySchema, namespace, options) {
|
|
2033
|
+
// 1. Explicit property mapping (highest precedence)
|
|
2034
|
+
if (options.propertyMapping?.[propertyName]) {
|
|
2035
|
+
return options.propertyMapping[propertyName];
|
|
2036
|
+
}
|
|
2037
|
+
// 2. x-ad4m metadata in property schema
|
|
2038
|
+
if (propertySchema["x-ad4m"]?.through) {
|
|
2039
|
+
return propertySchema["x-ad4m"].through;
|
|
2040
|
+
}
|
|
2041
|
+
// 3. Generate from namespace + property name
|
|
2042
|
+
if (options.predicateTemplate) {
|
|
2043
|
+
const normalizedNs = normalizeNamespaceString(namespace);
|
|
2044
|
+
const [scheme, rest] = normalizedNs.includes('://') ? normalizedNs.split('://') : ['', normalizedNs];
|
|
2045
|
+
const nsNoScheme = rest || '';
|
|
2046
|
+
return options.predicateTemplate
|
|
2047
|
+
.replace('${namespace}', nsNoScheme)
|
|
2048
|
+
.replace('${scheme}', scheme)
|
|
2049
|
+
.replace('${ns}', nsNoScheme)
|
|
2050
|
+
.replace('${title}', schema.title || '')
|
|
2051
|
+
.replace('${property}', propertyName);
|
|
2052
|
+
}
|
|
2053
|
+
// 4. Custom predicate generator
|
|
2054
|
+
if (options.predicateGenerator) {
|
|
2055
|
+
return options.predicateGenerator(schema.title || '', propertyName);
|
|
2056
|
+
}
|
|
2057
|
+
// 5. Default: namespace + property name
|
|
2058
|
+
const normalizedNs = normalizeNamespaceString(namespace);
|
|
2059
|
+
if (normalizedNs.includes('://')) {
|
|
2060
|
+
// For namespaces like "product://", append property directly
|
|
2061
|
+
return `${normalizedNs}${propertyName}`;
|
|
2062
|
+
}
|
|
2063
|
+
else {
|
|
2064
|
+
return `${normalizedNs}://${propertyName}`;
|
|
2065
|
+
}
|
|
2066
|
+
}
|
|
2067
|
+
/**
|
|
2068
|
+
* Gets property-specific options using cascading precedence
|
|
2069
|
+
*/
|
|
2070
|
+
static getPropertyOption(propertyName, propertySchema, options, optionName, defaultValue) {
|
|
2071
|
+
// 1. Property-specific options
|
|
2072
|
+
if (options.propertyOptions?.[propertyName]?.[optionName] !== undefined) {
|
|
2073
|
+
return options.propertyOptions[propertyName][optionName];
|
|
2074
|
+
}
|
|
2075
|
+
// 2. x-ad4m metadata in property
|
|
2076
|
+
if (propertySchema["x-ad4m"]?.[optionName] !== undefined) {
|
|
2077
|
+
return propertySchema["x-ad4m"][optionName];
|
|
2078
|
+
}
|
|
2079
|
+
// 3. Global option
|
|
2080
|
+
if (options[optionName] !== undefined) {
|
|
2081
|
+
return options[optionName];
|
|
2082
|
+
}
|
|
2083
|
+
// 4. Default value
|
|
2084
|
+
return defaultValue;
|
|
2085
|
+
}
|
|
2086
|
+
/**
|
|
2087
|
+
* Gets default value for a JSON Schema type
|
|
2088
|
+
*/
|
|
2089
|
+
static getDefaultValueForType(type) {
|
|
2090
|
+
switch (type) {
|
|
2091
|
+
case 'string': return '';
|
|
2092
|
+
case 'number': return 0;
|
|
2093
|
+
case 'integer': return 0;
|
|
2094
|
+
case 'boolean': return false;
|
|
2095
|
+
case 'array': return [];
|
|
2096
|
+
case 'object': return {};
|
|
2097
|
+
default: return '';
|
|
2098
|
+
}
|
|
2099
|
+
}
|
|
775
2100
|
}
|
|
776
2101
|
_Ad4mModel_baseExpression = new WeakMap(), _Ad4mModel_subjectClassName = new WeakMap(), _Ad4mModel_source = new WeakMap(), _Ad4mModel_perspective = new WeakMap();
|
|
777
2102
|
Ad4mModel.classNamesByClass = new WeakMap();
|
|
@@ -799,6 +2124,7 @@ export class ModelQueryBuilder {
|
|
|
799
2124
|
constructor(perspective, ctor, query) {
|
|
800
2125
|
this.queryParams = {};
|
|
801
2126
|
this.modelClassName = null;
|
|
2127
|
+
this.useSurrealDBFlag = true;
|
|
802
2128
|
this.perspective = perspective;
|
|
803
2129
|
this.ctor = ctor;
|
|
804
2130
|
if (query)
|
|
@@ -936,6 +2262,35 @@ export class ModelQueryBuilder {
|
|
|
936
2262
|
this.modelClassName = className;
|
|
937
2263
|
return this;
|
|
938
2264
|
}
|
|
2265
|
+
/**
|
|
2266
|
+
* Enables or disables SurrealDB query path.
|
|
2267
|
+
*
|
|
2268
|
+
* @param enabled - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
|
|
2269
|
+
* @returns The query builder for chaining
|
|
2270
|
+
*
|
|
2271
|
+
* @example
|
|
2272
|
+
* ```typescript
|
|
2273
|
+
* // Use SurrealDB (default)
|
|
2274
|
+
* const recipes = await Recipe.query(perspective)
|
|
2275
|
+
* .where({ category: "Dessert" })
|
|
2276
|
+
* .useSurrealDB(true)
|
|
2277
|
+
* .get();
|
|
2278
|
+
*
|
|
2279
|
+
* // Use Prolog (legacy)
|
|
2280
|
+
* const recipesProlog = await Recipe.query(perspective)
|
|
2281
|
+
* .where({ category: "Dessert" })
|
|
2282
|
+
* .useSurrealDB(false)
|
|
2283
|
+
* .get();
|
|
2284
|
+
* ```
|
|
2285
|
+
*
|
|
2286
|
+
* @remarks
|
|
2287
|
+
* Note: Subscriptions (subscribe(), countSubscribe(), paginateSubscribe()) default to SurrealDB live queries
|
|
2288
|
+
* if useSurrealDB(true) is set (default).
|
|
2289
|
+
*/
|
|
2290
|
+
useSurrealDB(enabled = true) {
|
|
2291
|
+
this.useSurrealDBFlag = enabled;
|
|
2292
|
+
return this;
|
|
2293
|
+
}
|
|
939
2294
|
/**
|
|
940
2295
|
* Executes the query once and returns the results.
|
|
941
2296
|
*
|
|
@@ -949,16 +2304,24 @@ export class ModelQueryBuilder {
|
|
|
949
2304
|
* ```
|
|
950
2305
|
*/
|
|
951
2306
|
async get() {
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
2307
|
+
if (this.useSurrealDBFlag) {
|
|
2308
|
+
const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
|
|
2309
|
+
const result = await this.perspective.querySurrealDB(surrealQuery);
|
|
2310
|
+
const { results } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
|
|
2311
|
+
return results;
|
|
2312
|
+
}
|
|
2313
|
+
else {
|
|
2314
|
+
const query = await this.ctor.queryToProlog(this.perspective, this.queryParams, this.modelClassName);
|
|
2315
|
+
const result = await this.perspective.infer(query);
|
|
2316
|
+
const { results } = await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, result);
|
|
2317
|
+
return results;
|
|
2318
|
+
}
|
|
956
2319
|
}
|
|
957
2320
|
/**
|
|
958
2321
|
* Subscribes to the query and receives updates when results change.
|
|
959
2322
|
*
|
|
960
2323
|
* This method:
|
|
961
|
-
* 1. Creates and initializes a
|
|
2324
|
+
* 1. Creates and initializes a SurrealDB live query subscription (default)
|
|
962
2325
|
* 2. Sets up the callback to process future updates
|
|
963
2326
|
* 3. Returns the initial results immediately
|
|
964
2327
|
*
|
|
@@ -980,19 +2343,41 @@ export class ModelQueryBuilder {
|
|
|
980
2343
|
* // When done with subscription:
|
|
981
2344
|
* builder.dispose();
|
|
982
2345
|
* ```
|
|
2346
|
+
*
|
|
2347
|
+
* @remarks
|
|
2348
|
+
* By default, this uses SurrealDB live queries for real-time updates.
|
|
2349
|
+
* Prolog subscriptions remain available via `.useSurrealDB(false)`.
|
|
983
2350
|
*/
|
|
984
2351
|
async subscribe(callback) {
|
|
985
2352
|
// Clean up any existing subscription
|
|
986
2353
|
this.dispose();
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
const
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
2354
|
+
if (this.useSurrealDBFlag) {
|
|
2355
|
+
const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
|
|
2356
|
+
this.currentSubscription = await this.perspective.subscribeSurrealDB(surrealQuery);
|
|
2357
|
+
const processResults = async (result) => {
|
|
2358
|
+
// The result from live query subscription update (handled in PerspectiveInstance listener)
|
|
2359
|
+
// is the new full set of results (because we re-query in Rust).
|
|
2360
|
+
// So we just need to map it to instances.
|
|
2361
|
+
const { results } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
|
|
2362
|
+
callback(results);
|
|
2363
|
+
};
|
|
2364
|
+
this.currentSubscription.onResult(processResults);
|
|
2365
|
+
// Process initial result
|
|
2366
|
+
const { results } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, this.currentSubscription.result);
|
|
2367
|
+
return results;
|
|
2368
|
+
}
|
|
2369
|
+
else {
|
|
2370
|
+
// Note: Subscriptions currently only work with Prolog
|
|
2371
|
+
const query = await this.ctor.queryToProlog(this.perspective, this.queryParams, this.modelClassName);
|
|
2372
|
+
this.currentSubscription = await this.perspective.subscribeInfer(query);
|
|
2373
|
+
const processResults = async (result) => {
|
|
2374
|
+
const { results } = await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, result);
|
|
2375
|
+
callback(results);
|
|
2376
|
+
};
|
|
2377
|
+
this.currentSubscription.onResult(processResults);
|
|
2378
|
+
const { results } = await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, this.currentSubscription.result);
|
|
2379
|
+
return results;
|
|
2380
|
+
}
|
|
996
2381
|
}
|
|
997
2382
|
/**
|
|
998
2383
|
* Gets the total count of matching entities.
|
|
@@ -1007,15 +2392,26 @@ export class ModelQueryBuilder {
|
|
|
1007
2392
|
* ```
|
|
1008
2393
|
*/
|
|
1009
2394
|
async count() {
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
2395
|
+
if (this.useSurrealDBFlag) {
|
|
2396
|
+
const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
|
|
2397
|
+
const result = await this.perspective.querySurrealDB(surrealQuery);
|
|
2398
|
+
// Use instancesFromSurrealResult to apply JS-level filtering for advanced where conditions
|
|
2399
|
+
// (e.g., gt, gte, lt, lte, between, contains on properties and author/timestamp)
|
|
2400
|
+
// This ensures count() returns the same number as get().length
|
|
2401
|
+
const { totalCount } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
|
|
2402
|
+
return totalCount;
|
|
2403
|
+
}
|
|
2404
|
+
else {
|
|
2405
|
+
const query = await this.ctor.countQueryToProlog(this.perspective, this.queryParams, this.modelClassName);
|
|
2406
|
+
const result = await this.perspective.infer(query);
|
|
2407
|
+
return result?.[0]?.TotalCount || 0;
|
|
2408
|
+
}
|
|
1013
2409
|
}
|
|
1014
2410
|
/**
|
|
1015
2411
|
* Subscribes to count updates for matching entities.
|
|
1016
2412
|
*
|
|
1017
2413
|
* This method:
|
|
1018
|
-
* 1. Creates and initializes a
|
|
2414
|
+
* 1. Creates and initializes a SurrealDB live query subscription for the count (default)
|
|
1019
2415
|
* 2. Sets up the callback to process future count updates
|
|
1020
2416
|
* 3. Returns the initial count immediately
|
|
1021
2417
|
*
|
|
@@ -1037,18 +2433,35 @@ export class ModelQueryBuilder {
|
|
|
1037
2433
|
* // When done with subscription:
|
|
1038
2434
|
* builder.dispose();
|
|
1039
2435
|
* ```
|
|
2436
|
+
*
|
|
2437
|
+
* @remarks
|
|
2438
|
+
* By default, this uses SurrealDB live queries for real-time updates.
|
|
2439
|
+
* Prolog subscriptions remain available via `.useSurrealDB(false)`.
|
|
1040
2440
|
*/
|
|
1041
2441
|
async countSubscribe(callback) {
|
|
1042
2442
|
// Clean up any existing subscription
|
|
1043
2443
|
this.dispose();
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
const
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
2444
|
+
if (this.useSurrealDBFlag) {
|
|
2445
|
+
const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
|
|
2446
|
+
this.currentSubscription = await this.perspective.subscribeSurrealDB(surrealQuery);
|
|
2447
|
+
const processResults = async (result) => {
|
|
2448
|
+
const { totalCount } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
|
|
2449
|
+
callback(totalCount);
|
|
2450
|
+
};
|
|
2451
|
+
this.currentSubscription.onResult(processResults);
|
|
2452
|
+
const { totalCount } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, this.currentSubscription.result);
|
|
2453
|
+
return totalCount;
|
|
2454
|
+
}
|
|
2455
|
+
else {
|
|
2456
|
+
const query = await this.ctor.countQueryToProlog(this.perspective, this.queryParams, this.modelClassName);
|
|
2457
|
+
this.currentSubscription = await this.perspective.subscribeInfer(query);
|
|
2458
|
+
const processResults = async (result) => {
|
|
2459
|
+
const newCount = result?.[0]?.TotalCount || 0;
|
|
2460
|
+
callback(newCount);
|
|
2461
|
+
};
|
|
2462
|
+
this.currentSubscription.onResult(processResults);
|
|
2463
|
+
return this.currentSubscription.result?.[0]?.TotalCount || 0;
|
|
2464
|
+
}
|
|
1052
2465
|
}
|
|
1053
2466
|
/**
|
|
1054
2467
|
* Gets a page of results with pagination metadata.
|
|
@@ -1067,16 +2480,24 @@ export class ModelQueryBuilder {
|
|
|
1067
2480
|
*/
|
|
1068
2481
|
async paginate(pageSize, pageNumber) {
|
|
1069
2482
|
const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
2483
|
+
if (this.useSurrealDBFlag) {
|
|
2484
|
+
const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, paginationQuery);
|
|
2485
|
+
const result = await this.perspective.querySurrealDB(surrealQuery);
|
|
2486
|
+
const { results, totalCount } = (await this.ctor.instancesFromSurrealResult(this.perspective, paginationQuery, result));
|
|
2487
|
+
return { results, totalCount, pageSize, pageNumber };
|
|
2488
|
+
}
|
|
2489
|
+
else {
|
|
2490
|
+
const prologQuery = await this.ctor.queryToProlog(this.perspective, paginationQuery, this.modelClassName);
|
|
2491
|
+
const result = await this.perspective.infer(prologQuery);
|
|
2492
|
+
const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, paginationQuery, result));
|
|
2493
|
+
return { results, totalCount, pageSize, pageNumber };
|
|
2494
|
+
}
|
|
1074
2495
|
}
|
|
1075
2496
|
/**
|
|
1076
2497
|
* Subscribes to paginated results updates.
|
|
1077
2498
|
*
|
|
1078
2499
|
* This method:
|
|
1079
|
-
* 1. Creates and initializes a
|
|
2500
|
+
* 1. Creates and initializes a SurrealDB live query subscription for the paginated results (default)
|
|
1080
2501
|
* 2. Sets up the callback to process future page updates
|
|
1081
2502
|
* 3. Returns the initial page immediately
|
|
1082
2503
|
*
|
|
@@ -1100,19 +2521,36 @@ export class ModelQueryBuilder {
|
|
|
1100
2521
|
* // When done with subscription:
|
|
1101
2522
|
* builder.dispose();
|
|
1102
2523
|
* ```
|
|
2524
|
+
*
|
|
2525
|
+
* @remarks
|
|
2526
|
+
* By default, this uses SurrealDB live queries for real-time updates.
|
|
2527
|
+
* Prolog subscriptions remain available via `.useSurrealDB(false)`.
|
|
1103
2528
|
*/
|
|
1104
2529
|
async paginateSubscribe(pageSize, pageNumber, callback) {
|
|
1105
2530
|
// Clean up any existing subscription
|
|
1106
2531
|
this.dispose();
|
|
1107
2532
|
const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
const
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
2533
|
+
if (this.useSurrealDBFlag) {
|
|
2534
|
+
const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, paginationQuery);
|
|
2535
|
+
this.currentSubscription = await this.perspective.subscribeSurrealDB(surrealQuery);
|
|
2536
|
+
const processResults = async (result) => {
|
|
2537
|
+
const { results, totalCount } = (await this.ctor.instancesFromSurrealResult(this.perspective, paginationQuery, result));
|
|
2538
|
+
callback({ results, totalCount, pageSize, pageNumber });
|
|
2539
|
+
};
|
|
2540
|
+
this.currentSubscription.onResult(processResults);
|
|
2541
|
+
const { results, totalCount } = (await this.ctor.instancesFromSurrealResult(this.perspective, paginationQuery, this.currentSubscription.result));
|
|
2542
|
+
return { results, totalCount, pageSize, pageNumber };
|
|
2543
|
+
}
|
|
2544
|
+
else {
|
|
2545
|
+
const prologQuery = await this.ctor.queryToProlog(this.perspective, paginationQuery, this.modelClassName);
|
|
2546
|
+
this.currentSubscription = await this.perspective.subscribeInfer(prologQuery);
|
|
2547
|
+
const processResults = async (r) => {
|
|
2548
|
+
const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, r));
|
|
2549
|
+
callback({ results, totalCount, pageSize, pageNumber });
|
|
2550
|
+
};
|
|
2551
|
+
this.currentSubscription.onResult(processResults);
|
|
2552
|
+
const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, paginationQuery, this.currentSubscription.result));
|
|
2553
|
+
return { results, totalCount, pageSize, pageNumber };
|
|
2554
|
+
}
|
|
1117
2555
|
}
|
|
1118
2556
|
}
|