@coasys/ad4m 0.10.1 → 0.11.1
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 +1744 -87
- package/lib/index.js +1744 -87
- package/lib/src/model/Ad4mModel.d.ts +423 -9
- package/lib/src/model/Ad4mModel.js +1527 -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 +1782 -87
- package/src/perspectives/PerspectiveClient.ts +67 -0
- package/src/perspectives/PerspectiveProxy.ts +175 -35
- package/src/perspectives/PerspectiveResolver.ts +8 -0
package/src/model/Ad4mModel.ts
CHANGED
|
@@ -1,8 +1,47 @@
|
|
|
1
1
|
import { Literal } from "../Literal";
|
|
2
2
|
import { Link } from "../links/Links";
|
|
3
3
|
import { PerspectiveProxy } from "../perspectives/PerspectiveProxy";
|
|
4
|
-
import { makeRandomPrologAtom } from "./decorators";
|
|
5
|
-
import { singularToPlural } from "./util";
|
|
4
|
+
import { makeRandomPrologAtom, PropertyOptions, CollectionOptions, ModelOptions } from "./decorators";
|
|
5
|
+
import { singularToPlural, pluralToSingular, propertyNameToSetterName, collectionToAdderName, collectionToRemoverName, collectionToSetterName } from "./util";
|
|
6
|
+
|
|
7
|
+
// JSON Schema type definitions
|
|
8
|
+
interface JSONSchemaProperty {
|
|
9
|
+
type: string | string[];
|
|
10
|
+
items?: JSONSchemaProperty;
|
|
11
|
+
properties?: { [key: string]: JSONSchemaProperty };
|
|
12
|
+
required?: string[];
|
|
13
|
+
"x-ad4m"?: {
|
|
14
|
+
through?: string;
|
|
15
|
+
resolveLanguage?: string;
|
|
16
|
+
local?: boolean;
|
|
17
|
+
writable?: boolean;
|
|
18
|
+
initial?: string;
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
interface JSONSchema {
|
|
23
|
+
$schema?: string;
|
|
24
|
+
title?: string;
|
|
25
|
+
$id?: string;
|
|
26
|
+
type?: string;
|
|
27
|
+
properties?: { [key: string]: JSONSchemaProperty };
|
|
28
|
+
required?: string[];
|
|
29
|
+
"x-ad4m"?: {
|
|
30
|
+
namespace?: string;
|
|
31
|
+
className?: string;
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
interface JSONSchemaToModelOptions {
|
|
36
|
+
name: string;
|
|
37
|
+
namespace?: string;
|
|
38
|
+
predicateTemplate?: string;
|
|
39
|
+
predicateGenerator?: (title: string, property: string) => string;
|
|
40
|
+
propertyMapping?: Record<string, string>;
|
|
41
|
+
resolveLanguage?: string;
|
|
42
|
+
local?: boolean;
|
|
43
|
+
propertyOptions?: Record<string, Partial<PropertyOptions>>;
|
|
44
|
+
}
|
|
6
45
|
|
|
7
46
|
type ValueTuple = [name: string, value: any, resolve?: boolean];
|
|
8
47
|
type WhereOps = {
|
|
@@ -12,6 +51,7 @@ type WhereOps = {
|
|
|
12
51
|
lte: number; // less than or equal to
|
|
13
52
|
gt: number; // greater than
|
|
14
53
|
gte: number; // greater than or equal to
|
|
54
|
+
contains: string | number; // substring/element check
|
|
15
55
|
};
|
|
16
56
|
type WhereCondition = string | number | boolean | string[] | number[] | { [K in keyof WhereOps]?: WhereOps[K] };
|
|
17
57
|
type Where = { [propertyName: string]: WhereCondition };
|
|
@@ -32,6 +72,60 @@ export type AllInstancesResult = { AllInstances: Ad4mModel[]; TotalCount?: numbe
|
|
|
32
72
|
export type ResultsWithTotalCount<T> = { results: T[]; totalCount?: number };
|
|
33
73
|
export type PaginationResult<T> = { results: T[]; totalCount?: number; pageSize: number; pageNumber: number };
|
|
34
74
|
|
|
75
|
+
/**
|
|
76
|
+
* Metadata for a single property extracted from decorators.
|
|
77
|
+
*/
|
|
78
|
+
export interface PropertyMetadata {
|
|
79
|
+
/** The property name */
|
|
80
|
+
name: string;
|
|
81
|
+
/** The predicate URI (through value) */
|
|
82
|
+
predicate: string;
|
|
83
|
+
/** Whether the property is required */
|
|
84
|
+
required: boolean;
|
|
85
|
+
/** Whether the property is writable */
|
|
86
|
+
writable: boolean;
|
|
87
|
+
/** Initial value if specified */
|
|
88
|
+
initial?: string;
|
|
89
|
+
/** Language for resolution (e.g., "literal") */
|
|
90
|
+
resolveLanguage?: string;
|
|
91
|
+
/** Custom Prolog getter code */
|
|
92
|
+
getter?: string;
|
|
93
|
+
/** Custom Prolog setter code */
|
|
94
|
+
setter?: string;
|
|
95
|
+
/** Whether stored locally only */
|
|
96
|
+
local?: boolean;
|
|
97
|
+
/** Transform function */
|
|
98
|
+
transform?: (value: any) => any;
|
|
99
|
+
/** Whether this is a flag property */
|
|
100
|
+
flag?: boolean;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Metadata for a single collection extracted from decorators.
|
|
105
|
+
*/
|
|
106
|
+
export interface CollectionMetadata {
|
|
107
|
+
/** The collection name */
|
|
108
|
+
name: string;
|
|
109
|
+
/** The predicate URI (through value) */
|
|
110
|
+
predicate: string;
|
|
111
|
+
/** Filter conditions */
|
|
112
|
+
where?: { isInstance?: any; condition?: string };
|
|
113
|
+
/** Whether stored locally only */
|
|
114
|
+
local?: boolean;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Complete model metadata extracted from decorators.
|
|
119
|
+
*/
|
|
120
|
+
export interface ModelMetadata {
|
|
121
|
+
/** The model class name from @ModelOptions */
|
|
122
|
+
className: string;
|
|
123
|
+
/** Map of property name to metadata */
|
|
124
|
+
properties: Record<string, PropertyMetadata>;
|
|
125
|
+
/** Map of collection name to metadata */
|
|
126
|
+
collections: Record<string, CollectionMetadata>;
|
|
127
|
+
}
|
|
128
|
+
|
|
35
129
|
function capitalize(word: string): string {
|
|
36
130
|
return word.charAt(0).toUpperCase() + word.slice(1);
|
|
37
131
|
}
|
|
@@ -171,6 +265,44 @@ function buildLimitQuery(limit?: number): string {
|
|
|
171
265
|
return `takeN(InstancesWithOffset, ${limit}, AllInstances)`;
|
|
172
266
|
}
|
|
173
267
|
|
|
268
|
+
function normalizeNamespaceString(namespace: string): string {
|
|
269
|
+
if (!namespace) return '';
|
|
270
|
+
if (namespace.includes('://')) {
|
|
271
|
+
const [scheme, rest] = namespace.split('://');
|
|
272
|
+
const path = (rest || '').replace(/\/+$/,'');
|
|
273
|
+
return `${scheme}://${path}`;
|
|
274
|
+
} else {
|
|
275
|
+
return namespace.replace(/\/+$/,'');
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
function normalizeSchemaType(type?: string | string[]): string | undefined {
|
|
280
|
+
if (!type) return undefined;
|
|
281
|
+
if (typeof type === "string") return type;
|
|
282
|
+
if (Array.isArray(type) && type.length > 0) {
|
|
283
|
+
const nonNull = type.find((t) => t !== "null");
|
|
284
|
+
return nonNull || type[0];
|
|
285
|
+
}
|
|
286
|
+
return undefined;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function isSchemaType(schema: JSONSchemaProperty, expectedType: string): boolean {
|
|
290
|
+
return normalizeSchemaType(schema.type) === expectedType;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
function isArrayType(schema: JSONSchemaProperty): boolean {
|
|
294
|
+
return isSchemaType(schema, "array");
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function isObjectType(schema: JSONSchemaProperty): boolean {
|
|
298
|
+
return isSchemaType(schema, "object");
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
function isNumericType(schema: JSONSchemaProperty): boolean {
|
|
302
|
+
const normalized = normalizeSchemaType(schema.type);
|
|
303
|
+
return normalized === "number" || normalized === "integer";
|
|
304
|
+
}
|
|
305
|
+
|
|
174
306
|
/**
|
|
175
307
|
* Base class for defining data models in AD4M.
|
|
176
308
|
*
|
|
@@ -305,6 +437,143 @@ export class Ad4mModel {
|
|
|
305
437
|
return classCache[perspectiveID];
|
|
306
438
|
}
|
|
307
439
|
|
|
440
|
+
/**
|
|
441
|
+
* Extracts metadata from decorators for query building.
|
|
442
|
+
*
|
|
443
|
+
* @description
|
|
444
|
+
* This method reads the metadata stored by decorators (@Property, @Collection, etc.)
|
|
445
|
+
* and returns it in a structured format that's easier to work with for query builders
|
|
446
|
+
* and other systems that need to introspect model structure.
|
|
447
|
+
*
|
|
448
|
+
* The metadata includes:
|
|
449
|
+
* - Class name from @ModelOptions
|
|
450
|
+
* - Property metadata (predicates, types, constraints, etc.)
|
|
451
|
+
* - Collection metadata (predicates, filters, etc.)
|
|
452
|
+
*
|
|
453
|
+
* For models created via `fromJSONSchema()`, this method will derive metadata from
|
|
454
|
+
* the stored `__properties` and `__collections` structures that were populated during
|
|
455
|
+
* the dynamic class creation. If these structures are empty but a JSON schema was
|
|
456
|
+
* attached to the class, it can fall back to deriving metadata from that schema.
|
|
457
|
+
*
|
|
458
|
+
* @returns Structured metadata object containing className, properties, and collections
|
|
459
|
+
* @throws Error if the class doesn't have @ModelOptions decorator
|
|
460
|
+
*
|
|
461
|
+
* @example
|
|
462
|
+
* ```typescript
|
|
463
|
+
* @ModelOptions({ name: "Recipe" })
|
|
464
|
+
* class Recipe extends Ad4mModel {
|
|
465
|
+
* @Property({ through: "recipe://name", resolveLanguage: "literal" })
|
|
466
|
+
* name: string = "";
|
|
467
|
+
*
|
|
468
|
+
* @Collection({ through: "recipe://ingredient" })
|
|
469
|
+
* ingredients: string[] = [];
|
|
470
|
+
* }
|
|
471
|
+
*
|
|
472
|
+
* const metadata = Recipe.getModelMetadata();
|
|
473
|
+
* console.log(metadata.className); // "Recipe"
|
|
474
|
+
* console.log(metadata.properties.name.predicate); // "recipe://name"
|
|
475
|
+
* console.log(metadata.collections.ingredients.predicate); // "recipe://ingredient"
|
|
476
|
+
* ```
|
|
477
|
+
*/
|
|
478
|
+
public static getModelMetadata(): ModelMetadata {
|
|
479
|
+
// Access the prototype with any type to access decorator-added properties
|
|
480
|
+
const prototype = this.prototype as any;
|
|
481
|
+
|
|
482
|
+
// Validate that the class has @ModelOptions decorator
|
|
483
|
+
// The decorator sets prototype.className, so we check for its existence
|
|
484
|
+
if (!prototype.className || prototype.className === 'Ad4mModel') {
|
|
485
|
+
throw new Error("Model class must be decorated with @ModelOptions");
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
// Extract className
|
|
489
|
+
const className = prototype.className;
|
|
490
|
+
|
|
491
|
+
// Extract properties from prototype.__properties
|
|
492
|
+
const propertiesMetadata: Record<string, PropertyMetadata> = {};
|
|
493
|
+
const prototypeProperties = prototype.__properties || {};
|
|
494
|
+
|
|
495
|
+
for (const [propertyName, opts] of Object.entries(prototypeProperties)) {
|
|
496
|
+
const options = opts as PropertyOptions & { required?: boolean; flag?: boolean };
|
|
497
|
+
propertiesMetadata[propertyName] = {
|
|
498
|
+
name: propertyName,
|
|
499
|
+
predicate: options.through || "",
|
|
500
|
+
required: options.required || false,
|
|
501
|
+
writable: options.writable || false,
|
|
502
|
+
...(options.initial !== undefined && { initial: options.initial }),
|
|
503
|
+
...(options.resolveLanguage !== undefined && { resolveLanguage: options.resolveLanguage }),
|
|
504
|
+
...(options.getter !== undefined && { getter: options.getter }),
|
|
505
|
+
...(options.setter !== undefined && { setter: options.setter }),
|
|
506
|
+
...(options.local !== undefined && { local: options.local }),
|
|
507
|
+
...(options.transform !== undefined && { transform: options.transform }),
|
|
508
|
+
...(options.flag !== undefined && { flag: options.flag })
|
|
509
|
+
};
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
// Extract collections from prototype.__collections
|
|
513
|
+
const collectionsMetadata: Record<string, CollectionMetadata> = {};
|
|
514
|
+
const prototypeCollections = prototype.__collections || {};
|
|
515
|
+
|
|
516
|
+
for (const [collectionName, opts] of Object.entries(prototypeCollections)) {
|
|
517
|
+
const options = opts as CollectionOptions;
|
|
518
|
+
collectionsMetadata[collectionName] = {
|
|
519
|
+
name: collectionName,
|
|
520
|
+
predicate: options.through || "",
|
|
521
|
+
...(options.where !== undefined && { where: options.where }),
|
|
522
|
+
...(options.local !== undefined && { local: options.local })
|
|
523
|
+
};
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
// Fallback: If both structures are empty but a JSON schema is attached, derive from it
|
|
527
|
+
// This handles edge cases where fromJSONSchema() was called but metadata wasn't properly populated
|
|
528
|
+
const hasProperties = Object.keys(propertiesMetadata).length > 0;
|
|
529
|
+
const hasCollections = Object.keys(collectionsMetadata).length > 0;
|
|
530
|
+
const hasMetadata = hasProperties || hasCollections;
|
|
531
|
+
|
|
532
|
+
if (!hasMetadata && prototype.__jsonSchema) {
|
|
533
|
+
// Derive metadata from the attached JSON schema
|
|
534
|
+
const schema = prototype.__jsonSchema;
|
|
535
|
+
const options = prototype.__jsonSchemaOptions || {};
|
|
536
|
+
|
|
537
|
+
if (schema.properties) {
|
|
538
|
+
for (const [propertyName, propertySchema] of Object.entries(schema.properties)) {
|
|
539
|
+
const isArray = isArrayType(propertySchema as JSONSchemaProperty);
|
|
540
|
+
const predicate = this.determinePredicate(
|
|
541
|
+
schema,
|
|
542
|
+
propertyName,
|
|
543
|
+
propertySchema as JSONSchemaProperty,
|
|
544
|
+
this.determineNamespace(schema, options),
|
|
545
|
+
options
|
|
546
|
+
);
|
|
547
|
+
|
|
548
|
+
if (isArray) {
|
|
549
|
+
collectionsMetadata[propertyName] = {
|
|
550
|
+
name: propertyName,
|
|
551
|
+
predicate: predicate,
|
|
552
|
+
...(propertySchema["x-ad4m"]?.local !== undefined && { local: propertySchema["x-ad4m"].local })
|
|
553
|
+
};
|
|
554
|
+
} else {
|
|
555
|
+
const isRequired = schema.required?.includes(propertyName) || false;
|
|
556
|
+
propertiesMetadata[propertyName] = {
|
|
557
|
+
name: propertyName,
|
|
558
|
+
predicate: predicate,
|
|
559
|
+
required: isRequired,
|
|
560
|
+
writable: propertySchema["x-ad4m"]?.writable !== false,
|
|
561
|
+
...(propertySchema["x-ad4m"]?.resolveLanguage && { resolveLanguage: propertySchema["x-ad4m"].resolveLanguage }),
|
|
562
|
+
...(propertySchema["x-ad4m"]?.initial && { initial: propertySchema["x-ad4m"].initial }),
|
|
563
|
+
...(propertySchema["x-ad4m"]?.local !== undefined && { local: propertySchema["x-ad4m"].local })
|
|
564
|
+
};
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
return {
|
|
571
|
+
className,
|
|
572
|
+
properties: propertiesMetadata,
|
|
573
|
+
collections: collectionsMetadata
|
|
574
|
+
};
|
|
575
|
+
}
|
|
576
|
+
|
|
308
577
|
/**
|
|
309
578
|
* Constructs a new model instance.
|
|
310
579
|
*
|
|
@@ -443,6 +712,506 @@ export class Ad4mModel {
|
|
|
443
712
|
return fullQuery;
|
|
444
713
|
}
|
|
445
714
|
|
|
715
|
+
/**
|
|
716
|
+
* Generates a SurrealQL query from a Query object.
|
|
717
|
+
*
|
|
718
|
+
* @description
|
|
719
|
+
* This method translates high-level query parameters into a SurrealQL query string
|
|
720
|
+
* that can be executed against the SurrealDB backend. Unlike Prolog queries which
|
|
721
|
+
* operate on SDNA-aware predicates, SurrealQL queries operate directly on raw links
|
|
722
|
+
* stored in SurrealDB.
|
|
723
|
+
*
|
|
724
|
+
* The generated query uses a CTE (Common Table Expression) pattern:
|
|
725
|
+
* 1. First, identify candidate base expressions by filtering links based on where conditions
|
|
726
|
+
* 2. Then, for each candidate base, resolve properties and collections via subqueries
|
|
727
|
+
* 3. Finally, apply ordering, pagination (LIMIT/START) at the SQL level
|
|
728
|
+
*
|
|
729
|
+
* Key architectural notes:
|
|
730
|
+
* - SurrealDB stores only raw links (source, predicate, target, author, timestamp)
|
|
731
|
+
* - No SDNA knowledge at the database level
|
|
732
|
+
* - Properties are resolved via subqueries that look for links with specific predicates
|
|
733
|
+
* - Collections are similar but return multiple values instead of one
|
|
734
|
+
* - Special fields (base, author, timestamp) are accessed directly, not via subqueries
|
|
735
|
+
*
|
|
736
|
+
* @param perspective - The perspective to query (used for metadata extraction)
|
|
737
|
+
* @param query - Query parameters (where, order, limit, offset, properties, collections)
|
|
738
|
+
* @returns Complete SurrealQL query string ready for execution
|
|
739
|
+
*
|
|
740
|
+
* @example
|
|
741
|
+
* ```typescript
|
|
742
|
+
* const query = Recipe.queryToSurrealQL(perspective, {
|
|
743
|
+
* where: { name: "Pasta", rating: { gt: 4 } },
|
|
744
|
+
* order: { timestamp: "DESC" },
|
|
745
|
+
* limit: 10
|
|
746
|
+
* });
|
|
747
|
+
* // Returns: SELECT source AS base, array::first(target[WHERE predicate = ...]) AS name, ...
|
|
748
|
+
* // FROM link WHERE ... GROUP BY source ORDER BY timestamp DESC LIMIT 10
|
|
749
|
+
* ```
|
|
750
|
+
*/
|
|
751
|
+
public static async queryToSurrealQL(perspective: PerspectiveProxy, query: Query): Promise<string> {
|
|
752
|
+
const metadata = this.getModelMetadata();
|
|
753
|
+
const { source, where, order, offset, limit } = query;
|
|
754
|
+
|
|
755
|
+
// Build list of graph traversal filters for required predicates
|
|
756
|
+
const graphTraversalFilters: string[] = [];
|
|
757
|
+
|
|
758
|
+
// Add source filter if specified (filter to nodes that are children of this source)
|
|
759
|
+
// Source filter means: find targets of 'ad4m://has_child' links from the specified source
|
|
760
|
+
if (source) {
|
|
761
|
+
// Use graph traversal: node must be target of has_child link from source
|
|
762
|
+
graphTraversalFilters.push(
|
|
763
|
+
`count(<-link[WHERE perspective = $perspective AND in.uri = ${this.formatSurrealValue(source)} AND predicate = 'ad4m://has_child']) > 0`
|
|
764
|
+
);
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
// Add filters for required properties
|
|
768
|
+
for (const [propName, propMeta] of Object.entries(metadata.properties)) {
|
|
769
|
+
if (propMeta.required) {
|
|
770
|
+
// For flag properties, also filter by the target value
|
|
771
|
+
if (propMeta.flag && propMeta.initial) {
|
|
772
|
+
graphTraversalFilters.push(
|
|
773
|
+
`count(->link[WHERE perspective = $perspective AND predicate = '${propMeta.predicate}' AND out.uri = '${propMeta.initial}']) > 0`
|
|
774
|
+
);
|
|
775
|
+
} else {
|
|
776
|
+
graphTraversalFilters.push(
|
|
777
|
+
`count(->link[WHERE perspective = $perspective AND predicate = '${propMeta.predicate}']) > 0`
|
|
778
|
+
);
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
// If no required properties, we need at least one property to define the model
|
|
784
|
+
// Use any property with an initial value as the defining characteristic
|
|
785
|
+
if (graphTraversalFilters.length === 0) {
|
|
786
|
+
for (const [propName, propMeta] of Object.entries(metadata.properties)) {
|
|
787
|
+
if (propMeta.initial) {
|
|
788
|
+
// For flag properties, also filter by the target value
|
|
789
|
+
if (propMeta.flag) {
|
|
790
|
+
graphTraversalFilters.push(
|
|
791
|
+
`count(->link[WHERE perspective = $perspective AND predicate = '${propMeta.predicate}' AND out.uri = '${propMeta.initial}']) > 0`
|
|
792
|
+
);
|
|
793
|
+
} else {
|
|
794
|
+
graphTraversalFilters.push(
|
|
795
|
+
`count(->link[WHERE perspective = $perspective AND predicate = '${propMeta.predicate}']) > 0`
|
|
796
|
+
);
|
|
797
|
+
}
|
|
798
|
+
break; // Just need one defining property
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
// Build user WHERE clause filters using graph traversal
|
|
804
|
+
const userWhereClause = this.buildGraphTraversalWhereClause(metadata, where);
|
|
805
|
+
|
|
806
|
+
// Build complete WHERE clause using graph traversal filters
|
|
807
|
+
const whereConditions: string[] = [];
|
|
808
|
+
|
|
809
|
+
// Add all graph traversal filters for required properties
|
|
810
|
+
whereConditions.push(...graphTraversalFilters);
|
|
811
|
+
|
|
812
|
+
// Add user where conditions if any
|
|
813
|
+
if (userWhereClause) {
|
|
814
|
+
whereConditions.push(userWhereClause);
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
// Always ensure node has at least one link in this perspective
|
|
818
|
+
whereConditions.push(`count(->link[WHERE perspective = $perspective]) > 0`);
|
|
819
|
+
|
|
820
|
+
// Build the query FROM node using direct graph traversal in WHERE
|
|
821
|
+
// This avoids slow subqueries and uses graph indexes for fast traversal
|
|
822
|
+
const fullQuery = `
|
|
823
|
+
SELECT
|
|
824
|
+
id AS source,
|
|
825
|
+
uri AS source_uri,
|
|
826
|
+
->link[WHERE perspective = $perspective] AS links
|
|
827
|
+
FROM node
|
|
828
|
+
WHERE ${whereConditions.join(' AND ')}
|
|
829
|
+
`.trim();
|
|
830
|
+
|
|
831
|
+
return fullQuery;
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
/**
|
|
835
|
+
* Builds the WHERE clause for SurrealQL queries using graph traversal syntax.
|
|
836
|
+
*
|
|
837
|
+
* @description
|
|
838
|
+
* Translates where conditions into graph traversal filters: `->link[WHERE ...]`
|
|
839
|
+
* This is more efficient than nested SELECTs because SurrealDB can optimize graph traversals.
|
|
840
|
+
*
|
|
841
|
+
* Handles several condition types:
|
|
842
|
+
* - Simple equality: `{ name: "Pasta" }` → `->link[WHERE predicate = 'X' AND out.uri = 'Pasta']`
|
|
843
|
+
* - Arrays (IN clause): `{ name: ["Pasta", "Pizza"] }` → `->link[WHERE predicate = 'X' AND out.uri IN [...]]`
|
|
844
|
+
* - NOT operators: Use `NOT` prefix
|
|
845
|
+
* - Comparison operators (gt, gte, lt, lte, etc.): Handled in post-query JavaScript filtering
|
|
846
|
+
* - Special fields: base uses `uri` directly, author/timestamp handled post-query
|
|
847
|
+
*
|
|
848
|
+
* @param metadata - Model metadata containing property predicates
|
|
849
|
+
* @param where - Where conditions from the query
|
|
850
|
+
* @returns Graph traversal WHERE clause filters, or empty string if no conditions
|
|
851
|
+
*
|
|
852
|
+
* @private
|
|
853
|
+
*/
|
|
854
|
+
private static buildGraphTraversalWhereClause(metadata: ModelMetadata, where?: Where): string {
|
|
855
|
+
if (!where) return '';
|
|
856
|
+
|
|
857
|
+
const conditions: string[] = [];
|
|
858
|
+
|
|
859
|
+
for (const [propertyName, condition] of Object.entries(where)) {
|
|
860
|
+
// Check if this is a special field (base, author, timestamp)
|
|
861
|
+
// Note: author and timestamp filtering is done in JavaScript after query
|
|
862
|
+
const isSpecial = ['base', 'author', 'timestamp'].includes(propertyName);
|
|
863
|
+
|
|
864
|
+
if (isSpecial) {
|
|
865
|
+
// Skip author and timestamp - they'll be filtered in JavaScript
|
|
866
|
+
// Only handle 'base' (which maps to 'uri') here
|
|
867
|
+
if (propertyName === 'author' || propertyName === 'timestamp') {
|
|
868
|
+
continue; // Skip - will be filtered post-query
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
const columnName = 'uri'; // base maps to uri in node table
|
|
872
|
+
|
|
873
|
+
// Handle base/uri field directly
|
|
874
|
+
if (Array.isArray(condition)) {
|
|
875
|
+
// Array values (IN clause)
|
|
876
|
+
const formattedValues = condition.map(v => this.formatSurrealValue(v)).join(', ');
|
|
877
|
+
conditions.push(`${columnName} IN [${formattedValues}]`);
|
|
878
|
+
} else if (typeof condition === 'object' && condition !== null) {
|
|
879
|
+
// Operator object
|
|
880
|
+
const ops = condition as any;
|
|
881
|
+
if (ops.not !== undefined) {
|
|
882
|
+
if (Array.isArray(ops.not)) {
|
|
883
|
+
const formattedValues = ops.not.map(v => this.formatSurrealValue(v)).join(', ');
|
|
884
|
+
conditions.push(`${columnName} NOT IN [${formattedValues}]`);
|
|
885
|
+
} else {
|
|
886
|
+
conditions.push(`${columnName} != ${this.formatSurrealValue(ops.not)}`);
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
if (ops.between !== undefined && Array.isArray(ops.between) && ops.between.length === 2) {
|
|
890
|
+
conditions.push(`${columnName} >= ${this.formatSurrealValue(ops.between[0])} AND ${columnName} <= ${this.formatSurrealValue(ops.between[1])}`);
|
|
891
|
+
}
|
|
892
|
+
if (ops.gt !== undefined) {
|
|
893
|
+
conditions.push(`${columnName} > ${this.formatSurrealValue(ops.gt)}`);
|
|
894
|
+
}
|
|
895
|
+
if (ops.gte !== undefined) {
|
|
896
|
+
conditions.push(`${columnName} >= ${this.formatSurrealValue(ops.gte)}`);
|
|
897
|
+
}
|
|
898
|
+
if (ops.lt !== undefined) {
|
|
899
|
+
conditions.push(`${columnName} < ${this.formatSurrealValue(ops.lt)}`);
|
|
900
|
+
}
|
|
901
|
+
if (ops.lte !== undefined) {
|
|
902
|
+
conditions.push(`${columnName} <= ${this.formatSurrealValue(ops.lte)}`);
|
|
903
|
+
}
|
|
904
|
+
if (ops.contains !== undefined) {
|
|
905
|
+
conditions.push(`${columnName} CONTAINS ${this.formatSurrealValue(ops.contains)}`);
|
|
906
|
+
}
|
|
907
|
+
} else {
|
|
908
|
+
// Simple equality
|
|
909
|
+
conditions.push(`${columnName} = ${this.formatSurrealValue(condition)}`);
|
|
910
|
+
}
|
|
911
|
+
} else {
|
|
912
|
+
// Handle regular properties via graph traversal
|
|
913
|
+
const propMeta = metadata.properties[propertyName];
|
|
914
|
+
if (!propMeta) continue; // Skip if property not found in metadata
|
|
915
|
+
|
|
916
|
+
const predicate = propMeta.predicate;
|
|
917
|
+
// Use fn::parse_literal() for properties with resolveLanguage
|
|
918
|
+
const targetField = propMeta.resolveLanguage === 'literal' ? 'fn::parse_literal(out.uri)' : 'out.uri';
|
|
919
|
+
|
|
920
|
+
if (Array.isArray(condition)) {
|
|
921
|
+
// Array values (IN clause)
|
|
922
|
+
const formattedValues = condition.map(v => this.formatSurrealValue(v)).join(', ');
|
|
923
|
+
conditions.push(`count(->link[WHERE perspective = $perspective AND predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) > 0`);
|
|
924
|
+
} else if (typeof condition === 'object' && condition !== null) {
|
|
925
|
+
// Operator object
|
|
926
|
+
const ops = condition as any;
|
|
927
|
+
if (ops.not !== undefined) {
|
|
928
|
+
if (Array.isArray(ops.not)) {
|
|
929
|
+
// For NOT IN with array: must NOT have a link with value in the array
|
|
930
|
+
const formattedValues = ops.not.map(v => this.formatSurrealValue(v)).join(', ');
|
|
931
|
+
conditions.push(`count(->link[WHERE perspective = $perspective AND predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) = 0`);
|
|
932
|
+
} else {
|
|
933
|
+
// For NOT with single value: must NOT have this value
|
|
934
|
+
conditions.push(`count(->link[WHERE perspective = $perspective AND predicate = '${predicate}' AND ${targetField} = ${this.formatSurrealValue(ops.not)}]) = 0`);
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
// Note: gt, gte, lt, lte, between, contains operators are filtered in JavaScript
|
|
938
|
+
// post-query because fn::parse_literal() comparisons in SurrealDB
|
|
939
|
+
// don't work reliably with numeric comparisons.
|
|
940
|
+
// These are handled in instancesFromSurrealResult along with author/timestamp filtering.
|
|
941
|
+
// However, we still need to ensure the property exists
|
|
942
|
+
const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
|
|
943
|
+
ops.lt !== undefined || ops.lte !== undefined ||
|
|
944
|
+
ops.between !== undefined || ops.contains !== undefined;
|
|
945
|
+
if (hasComparisonOps) {
|
|
946
|
+
// Ensure we only get nodes that have this property
|
|
947
|
+
conditions.push(`count(->link[WHERE perspective = $perspective AND predicate = '${predicate}']) > 0`);
|
|
948
|
+
}
|
|
949
|
+
} else {
|
|
950
|
+
// Simple equality
|
|
951
|
+
conditions.push(`count(->link[WHERE perspective = $perspective AND predicate = '${predicate}' AND ${targetField} = ${this.formatSurrealValue(condition)}]) > 0`);
|
|
952
|
+
}
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
return conditions.join(' AND ');
|
|
957
|
+
}
|
|
958
|
+
|
|
959
|
+
/**
|
|
960
|
+
* Builds the WHERE clause for SurrealQL queries.
|
|
961
|
+
*
|
|
962
|
+
* @description
|
|
963
|
+
* Translates the where conditions from the Query object into SurrealQL WHERE clause fragments.
|
|
964
|
+
* For each property filter, generates a subquery that checks for links with the appropriate
|
|
965
|
+
* predicate and target value.
|
|
966
|
+
*
|
|
967
|
+
* Handles several condition types:
|
|
968
|
+
* - Simple equality: `{ name: "Pasta" }` → subquery checking for predicate and target match
|
|
969
|
+
* - Arrays (IN clause): `{ name: ["Pasta", "Pizza"] }` → target IN [...]
|
|
970
|
+
* - Operators: `{ rating: { gt: 4 } }` → target > '4'
|
|
971
|
+
* - gt, gte, lt, lte: comparison operators
|
|
972
|
+
* - not: negation (single value or array)
|
|
973
|
+
* - between: range check
|
|
974
|
+
* - contains: substring/element check (uses SurrealQL CONTAINS)
|
|
975
|
+
* - Special fields: base, author, timestamp are accessed directly, not via subqueries
|
|
976
|
+
*
|
|
977
|
+
* All conditions are joined with AND.
|
|
978
|
+
*
|
|
979
|
+
* @param metadata - Model metadata containing property predicates
|
|
980
|
+
* @param where - Where conditions from the query
|
|
981
|
+
* @returns WHERE clause string (without the "WHERE" keyword), or empty string if no conditions
|
|
982
|
+
*
|
|
983
|
+
* @private
|
|
984
|
+
*/
|
|
985
|
+
private static buildSurrealWhereClause(metadata: ModelMetadata, where?: Where): string {
|
|
986
|
+
if (!where) return '';
|
|
987
|
+
|
|
988
|
+
const conditions: string[] = [];
|
|
989
|
+
|
|
990
|
+
for (const [propertyName, condition] of Object.entries(where)) {
|
|
991
|
+
// Check if this is a special field (base, author, timestamp)
|
|
992
|
+
// Note: author and timestamp filtering is done in JavaScript after GROUP BY
|
|
993
|
+
// because they need to be computed from the grouped links first
|
|
994
|
+
const isSpecial = ['base', 'author', 'timestamp'].includes(propertyName);
|
|
995
|
+
|
|
996
|
+
if (isSpecial) {
|
|
997
|
+
// Skip author and timestamp - they'll be filtered in JavaScript
|
|
998
|
+
// Only handle 'base' (which maps to 'source') here
|
|
999
|
+
if (propertyName === 'author' || propertyName === 'timestamp') {
|
|
1000
|
+
continue; // Skip - will be filtered post-query
|
|
1001
|
+
}
|
|
1002
|
+
|
|
1003
|
+
const columnName = 'source'; // base maps to source
|
|
1004
|
+
|
|
1005
|
+
// Handle base/source field directly
|
|
1006
|
+
if (Array.isArray(condition)) {
|
|
1007
|
+
// Array values (IN clause)
|
|
1008
|
+
const formattedValues = condition.map(v => this.formatSurrealValue(v)).join(', ');
|
|
1009
|
+
conditions.push(`${columnName} IN [${formattedValues}]`);
|
|
1010
|
+
} else if (typeof condition === 'object' && condition !== null) {
|
|
1011
|
+
// Operator object
|
|
1012
|
+
const ops = condition as any;
|
|
1013
|
+
if (ops.not !== undefined) {
|
|
1014
|
+
if (Array.isArray(ops.not)) {
|
|
1015
|
+
const formattedValues = ops.not.map(v => this.formatSurrealValue(v)).join(', ');
|
|
1016
|
+
conditions.push(`${columnName} NOT IN [${formattedValues}]`);
|
|
1017
|
+
} else {
|
|
1018
|
+
conditions.push(`${columnName} != ${this.formatSurrealValue(ops.not)}`);
|
|
1019
|
+
}
|
|
1020
|
+
}
|
|
1021
|
+
if (ops.between !== undefined && Array.isArray(ops.between) && ops.between.length === 2) {
|
|
1022
|
+
conditions.push(`${columnName} >= ${this.formatSurrealValue(ops.between[0])} AND ${columnName} <= ${this.formatSurrealValue(ops.between[1])}`);
|
|
1023
|
+
}
|
|
1024
|
+
if (ops.gt !== undefined) {
|
|
1025
|
+
conditions.push(`${columnName} > ${this.formatSurrealValue(ops.gt)}`);
|
|
1026
|
+
}
|
|
1027
|
+
if (ops.gte !== undefined) {
|
|
1028
|
+
conditions.push(`${columnName} >= ${this.formatSurrealValue(ops.gte)}`);
|
|
1029
|
+
}
|
|
1030
|
+
if (ops.lt !== undefined) {
|
|
1031
|
+
conditions.push(`${columnName} < ${this.formatSurrealValue(ops.lt)}`);
|
|
1032
|
+
}
|
|
1033
|
+
if (ops.lte !== undefined) {
|
|
1034
|
+
conditions.push(`${columnName} <= ${this.formatSurrealValue(ops.lte)}`);
|
|
1035
|
+
}
|
|
1036
|
+
if (ops.contains !== undefined) {
|
|
1037
|
+
conditions.push(`${columnName} CONTAINS ${this.formatSurrealValue(ops.contains)}`);
|
|
1038
|
+
}
|
|
1039
|
+
} else {
|
|
1040
|
+
// Simple equality
|
|
1041
|
+
conditions.push(`${columnName} = ${this.formatSurrealValue(condition)}`);
|
|
1042
|
+
}
|
|
1043
|
+
} else {
|
|
1044
|
+
// Handle regular properties via subqueries
|
|
1045
|
+
const propMeta = metadata.properties[propertyName];
|
|
1046
|
+
if (!propMeta) continue; // Skip if property not found in metadata
|
|
1047
|
+
|
|
1048
|
+
const predicate = propMeta.predicate;
|
|
1049
|
+
// Use fn::parse_literal() for properties with resolveLanguage
|
|
1050
|
+
const targetField = propMeta.resolveLanguage === 'literal' ? 'fn::parse_literal(target)' : 'target';
|
|
1051
|
+
|
|
1052
|
+
if (Array.isArray(condition)) {
|
|
1053
|
+
// Array values (IN clause)
|
|
1054
|
+
const formattedValues = condition.map(v => this.formatSurrealValue(v)).join(', ');
|
|
1055
|
+
conditions.push(`source IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}])`);
|
|
1056
|
+
} else if (typeof condition === 'object' && condition !== null) {
|
|
1057
|
+
// Operator object
|
|
1058
|
+
const ops = condition as any;
|
|
1059
|
+
if (ops.not !== undefined) {
|
|
1060
|
+
if (Array.isArray(ops.not)) {
|
|
1061
|
+
// For NOT IN with array: exclude sources that HAVE a value in the array
|
|
1062
|
+
const formattedValues = ops.not.map(v => this.formatSurrealValue(v)).join(', ');
|
|
1063
|
+
conditions.push(`source NOT IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}])`);
|
|
1064
|
+
} else {
|
|
1065
|
+
// For NOT with single value: exclude sources that HAVE this value
|
|
1066
|
+
conditions.push(`source NOT IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}' AND ${targetField} = ${this.formatSurrealValue(ops.not)})`);
|
|
1067
|
+
}
|
|
1068
|
+
}
|
|
1069
|
+
// Note: gt, gte, lt, lte, between, contains operators are filtered in JavaScript
|
|
1070
|
+
// post-query because fn::parse_literal() comparisons in SurrealDB subqueries
|
|
1071
|
+
// don't work reliably with numeric comparisons.
|
|
1072
|
+
// These are handled in instancesFromSurrealResult along with author/timestamp filtering.
|
|
1073
|
+
// However, we still need to ensure the property exists by filtering on the predicate
|
|
1074
|
+
const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
|
|
1075
|
+
ops.lt !== undefined || ops.lte !== undefined ||
|
|
1076
|
+
ops.between !== undefined || ops.contains !== undefined;
|
|
1077
|
+
if (hasComparisonOps) {
|
|
1078
|
+
// Ensure we only get instances that have this property
|
|
1079
|
+
conditions.push(`source IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}')`);
|
|
1080
|
+
}
|
|
1081
|
+
} else {
|
|
1082
|
+
// Simple equality
|
|
1083
|
+
conditions.push(`source IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}' AND ${targetField} = ${this.formatSurrealValue(condition)})`);
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
|
|
1088
|
+
return conditions.join(' AND ');
|
|
1089
|
+
}
|
|
1090
|
+
|
|
1091
|
+
/**
|
|
1092
|
+
* Builds the SELECT fields for SurrealQL queries.
|
|
1093
|
+
*
|
|
1094
|
+
* @description
|
|
1095
|
+
* Generates the field list for the SELECT clause, resolving properties and collections
|
|
1096
|
+
* via subqueries. Each property is fetched with a subquery that finds the link with the
|
|
1097
|
+
* appropriate predicate and returns its target. Collections are similar but don't use LIMIT 1.
|
|
1098
|
+
*
|
|
1099
|
+
* Field types:
|
|
1100
|
+
* - Properties: `(SELECT VALUE target FROM link WHERE source = $parent.base AND predicate = 'X' LIMIT 1) AS propName`
|
|
1101
|
+
* - Collections: `(SELECT VALUE target FROM link WHERE source = $parent.base AND predicate = 'X') AS collName`
|
|
1102
|
+
* - Author/Timestamp: Always included to provide metadata about each instance
|
|
1103
|
+
*
|
|
1104
|
+
* If properties or collections arrays are provided, only those fields are included.
|
|
1105
|
+
* Otherwise, all properties/collections from metadata are included.
|
|
1106
|
+
*
|
|
1107
|
+
* @param metadata - Model metadata containing property and collection predicates
|
|
1108
|
+
* @param properties - Optional array of property names to include (default: all)
|
|
1109
|
+
* @param collections - Optional array of collection names to include (default: all)
|
|
1110
|
+
* @returns Comma-separated SELECT field list
|
|
1111
|
+
*
|
|
1112
|
+
* @private
|
|
1113
|
+
*/
|
|
1114
|
+
private static buildSurrealSelectFields(metadata: ModelMetadata, properties?: string[], collections?: string[]): string {
|
|
1115
|
+
const fields: string[] = [];
|
|
1116
|
+
|
|
1117
|
+
// Determine properties to fetch
|
|
1118
|
+
const propsToFetch = properties || Object.keys(metadata.properties);
|
|
1119
|
+
for (const propName of propsToFetch) {
|
|
1120
|
+
const propMeta = metadata.properties[propName];
|
|
1121
|
+
if (!propMeta) continue; // Skip if not found
|
|
1122
|
+
|
|
1123
|
+
// Reference source directly since we're selecting from link table
|
|
1124
|
+
fields.push(`(SELECT VALUE target FROM link WHERE source = source AND predicate = '${propMeta.predicate}' LIMIT 1) AS ${propName}`);
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
|
+
// Determine collections to fetch
|
|
1128
|
+
const collsToFetch = collections || Object.keys(metadata.collections);
|
|
1129
|
+
for (const collName of collsToFetch) {
|
|
1130
|
+
const collMeta = metadata.collections[collName];
|
|
1131
|
+
if (!collMeta) continue; // Skip if not found
|
|
1132
|
+
|
|
1133
|
+
// Reference source directly since we're selecting from link table
|
|
1134
|
+
fields.push(`(SELECT VALUE target FROM link WHERE source = source AND predicate = '${collMeta.predicate}') AS ${collName}`);
|
|
1135
|
+
}
|
|
1136
|
+
|
|
1137
|
+
// Always add author and timestamp fields
|
|
1138
|
+
fields.push(`(SELECT VALUE author FROM link WHERE source = source LIMIT 1) AS author`);
|
|
1139
|
+
fields.push(`(SELECT VALUE timestamp FROM link WHERE source = source LIMIT 1) AS timestamp`);
|
|
1140
|
+
|
|
1141
|
+
return fields.join(',\n ');
|
|
1142
|
+
}
|
|
1143
|
+
|
|
1144
|
+
/**
|
|
1145
|
+
* Builds the SELECT fields for SurrealQL queries using aggregation functions.
|
|
1146
|
+
* Compatible with GROUP BY source queries.
|
|
1147
|
+
*
|
|
1148
|
+
* @private
|
|
1149
|
+
*/
|
|
1150
|
+
private static buildSurrealSelectFieldsWithAggregation(metadata: ModelMetadata, properties?: string[], collections?: string[]): string {
|
|
1151
|
+
const fields: string[] = [];
|
|
1152
|
+
|
|
1153
|
+
// Determine properties to fetch
|
|
1154
|
+
const propsToFetch = properties || Object.keys(metadata.properties);
|
|
1155
|
+
for (const propName of propsToFetch) {
|
|
1156
|
+
const propMeta = metadata.properties[propName];
|
|
1157
|
+
if (!propMeta) continue; // Skip if not found
|
|
1158
|
+
|
|
1159
|
+
// Use array::first to get the first target value for this predicate
|
|
1160
|
+
fields.push(`array::first(target[WHERE predicate = '${propMeta.predicate}']) AS ${propName}`);
|
|
1161
|
+
}
|
|
1162
|
+
|
|
1163
|
+
// Determine collections to fetch
|
|
1164
|
+
const collsToFetch = collections || Object.keys(metadata.collections);
|
|
1165
|
+
for (const collName of collsToFetch) {
|
|
1166
|
+
const collMeta = metadata.collections[collName];
|
|
1167
|
+
if (!collMeta) continue; // Skip if not found
|
|
1168
|
+
|
|
1169
|
+
// Use array filtering to get all target values for this predicate
|
|
1170
|
+
fields.push(`target[WHERE predicate = '${collMeta.predicate}'] AS ${collName}`);
|
|
1171
|
+
}
|
|
1172
|
+
|
|
1173
|
+
// Always add author and timestamp fields using array::first
|
|
1174
|
+
fields.push(`array::first(author) AS author`);
|
|
1175
|
+
fields.push(`array::first(timestamp) AS timestamp`);
|
|
1176
|
+
|
|
1177
|
+
return fields.join(',\n ');
|
|
1178
|
+
}
|
|
1179
|
+
|
|
1180
|
+
|
|
1181
|
+
/**
|
|
1182
|
+
* Formats a value for use in SurrealQL queries.
|
|
1183
|
+
*
|
|
1184
|
+
* @description
|
|
1185
|
+
* Handles different value types:
|
|
1186
|
+
* - Strings: Wrapped in single quotes with backslash-escaped special characters
|
|
1187
|
+
* - Numbers/booleans: Converted to string
|
|
1188
|
+
* - Arrays: Recursively formatted and wrapped in brackets
|
|
1189
|
+
*
|
|
1190
|
+
* @param value - The value to format
|
|
1191
|
+
* @returns Formatted value string ready for SurrealQL
|
|
1192
|
+
*
|
|
1193
|
+
* @private
|
|
1194
|
+
*/
|
|
1195
|
+
private static formatSurrealValue(value: any): string {
|
|
1196
|
+
if (typeof value === 'string') {
|
|
1197
|
+
// Escape backslashes first, then single quotes and other special characters
|
|
1198
|
+
const escaped = value
|
|
1199
|
+
.replace(/\\/g, '\\\\') // Backslash -> \\
|
|
1200
|
+
.replace(/'/g, "\\'") // Single quote -> \'
|
|
1201
|
+
.replace(/"/g, '\\"') // Double quote -> \"
|
|
1202
|
+
.replace(/\n/g, '\\n') // Newline -> \n
|
|
1203
|
+
.replace(/\r/g, '\\r') // Carriage return -> \r
|
|
1204
|
+
.replace(/\t/g, '\\t'); // Tab -> \t
|
|
1205
|
+
return `'${escaped}'`;
|
|
1206
|
+
} else if (typeof value === 'number' || typeof value === 'boolean') {
|
|
1207
|
+
return String(value);
|
|
1208
|
+
} else if (Array.isArray(value)) {
|
|
1209
|
+
return `[${value.map(v => this.formatSurrealValue(v)).join(', ')}]`;
|
|
1210
|
+
} else {
|
|
1211
|
+
return String(value);
|
|
1212
|
+
}
|
|
1213
|
+
}
|
|
1214
|
+
|
|
446
1215
|
public static async instancesFromPrologResult<T extends Ad4mModel>(
|
|
447
1216
|
this: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
448
1217
|
perspective: PerspectiveProxy,
|
|
@@ -477,19 +1246,394 @@ export class Ad4mModel {
|
|
|
477
1246
|
return { results: allInstances.filter((instance) => instance !== null), totalCount: result[0].TotalCount };
|
|
478
1247
|
}
|
|
479
1248
|
|
|
1249
|
+
/**
|
|
1250
|
+
* Converts SurrealDB query results to Ad4mModel instances.
|
|
1251
|
+
*
|
|
1252
|
+
* @param perspective - The perspective context
|
|
1253
|
+
* @param query - The query parameters used
|
|
1254
|
+
* @param result - Array of result objects from SurrealDB
|
|
1255
|
+
* @returns Promise resolving to results with total count
|
|
1256
|
+
*
|
|
1257
|
+
* @internal
|
|
1258
|
+
*/
|
|
1259
|
+
public static async instancesFromSurrealResult<T extends Ad4mModel>(
|
|
1260
|
+
this: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
1261
|
+
perspective: PerspectiveProxy,
|
|
1262
|
+
query: Query,
|
|
1263
|
+
result: any[]
|
|
1264
|
+
): Promise<ResultsWithTotalCount<T>> {
|
|
1265
|
+
if (!result || result.length === 0) return { results: [], totalCount: 0 };
|
|
1266
|
+
|
|
1267
|
+
const metadata = this.getModelMetadata();
|
|
1268
|
+
const requestedProperties = query?.properties || [];
|
|
1269
|
+
const requestedCollections = query?.collections || [];
|
|
1270
|
+
|
|
1271
|
+
// The query used GROUP BY with graph traversal, so each row has:
|
|
1272
|
+
// - source: the node ID (e.g., "node:abc123")
|
|
1273
|
+
// - source_uri: the actual URI (the base expression)
|
|
1274
|
+
// - links: array of link objects with {predicate, target, author, timestamp}
|
|
1275
|
+
|
|
1276
|
+
const instances: T[] = [];
|
|
1277
|
+
for (const row of result) {
|
|
1278
|
+
let base;
|
|
1279
|
+
try {
|
|
1280
|
+
// Use source_uri as the base (the actual URI), not the node ID
|
|
1281
|
+
base = row.source_uri;
|
|
1282
|
+
|
|
1283
|
+
// Skip rows without a source_uri field
|
|
1284
|
+
if (!base) {
|
|
1285
|
+
continue;
|
|
1286
|
+
}
|
|
1287
|
+
|
|
1288
|
+
const links = row.links || [];
|
|
1289
|
+
|
|
1290
|
+
const instance = new this(perspective, base) as any;
|
|
1291
|
+
|
|
1292
|
+
// Track the most recent timestamp and corresponding author
|
|
1293
|
+
let maxTimestamp = null;
|
|
1294
|
+
let latestAuthor = null;
|
|
1295
|
+
|
|
1296
|
+
// Process each link (track index for collection ordering)
|
|
1297
|
+
for (let linkIndex = 0; linkIndex < links.length; linkIndex++) {
|
|
1298
|
+
const link = links[linkIndex];
|
|
1299
|
+
const predicate = link.predicate;
|
|
1300
|
+
const target = link.target;
|
|
1301
|
+
|
|
1302
|
+
// Skip 'None' values
|
|
1303
|
+
if (target === 'None') continue;
|
|
1304
|
+
|
|
1305
|
+
// Track the most recent timestamp and its author
|
|
1306
|
+
if (link.timestamp && (!maxTimestamp || link.timestamp > maxTimestamp)) {
|
|
1307
|
+
maxTimestamp = link.timestamp;
|
|
1308
|
+
latestAuthor = link.author;
|
|
1309
|
+
}
|
|
1310
|
+
|
|
1311
|
+
// Find matching property
|
|
1312
|
+
let foundProperty = false;
|
|
1313
|
+
for (const [propName, propMeta] of Object.entries(metadata.properties)) {
|
|
1314
|
+
if (propMeta.predicate === predicate) {
|
|
1315
|
+
// For properties, take the first value (or we could use timestamp to get latest)
|
|
1316
|
+
// Note: Empty objects {} are truthy, so we need to check for them explicitly
|
|
1317
|
+
const currentValue = instance[propName];
|
|
1318
|
+
const isEmptyObject = typeof currentValue === 'object' && currentValue !== null && !Array.isArray(currentValue) && Object.keys(currentValue).length === 0;
|
|
1319
|
+
if (!currentValue || currentValue === "" || currentValue === 0 || isEmptyObject) {
|
|
1320
|
+
let convertedValue = target;
|
|
1321
|
+
|
|
1322
|
+
// Only process if target has a value
|
|
1323
|
+
if (target !== undefined && target !== null) {
|
|
1324
|
+
// Check if we need to resolve a non-literal language expression
|
|
1325
|
+
if (propMeta.resolveLanguage != undefined && propMeta.resolveLanguage !== 'literal' && typeof target === 'string') {
|
|
1326
|
+
// For non-literal languages, resolve the expression via perspective.getExpression()
|
|
1327
|
+
// Note: Literals are already parsed by SurrealDB's fn::parse_literal()
|
|
1328
|
+
try {
|
|
1329
|
+
const expression = await perspective.getExpression(target);
|
|
1330
|
+
if (expression) {
|
|
1331
|
+
// Parse the expression data if it's a JSON string
|
|
1332
|
+
try {
|
|
1333
|
+
convertedValue = JSON.parse(expression.data);
|
|
1334
|
+
} catch {
|
|
1335
|
+
// If parsing fails, use the data as-is
|
|
1336
|
+
convertedValue = expression.data;
|
|
1337
|
+
}
|
|
1338
|
+
}
|
|
1339
|
+
} catch (e) {
|
|
1340
|
+
console.warn(`Failed to resolve expression for ${propName}:`, e);
|
|
1341
|
+
convertedValue = target; // Fall back to raw value
|
|
1342
|
+
}
|
|
1343
|
+
} else if (typeof target === 'string' && target.startsWith('literal://')) {
|
|
1344
|
+
// Fallback: If we somehow got a literal URL that wasn't parsed by SurrealDB, parse it now
|
|
1345
|
+
try {
|
|
1346
|
+
const parsed = Literal.fromUrl(target).get();
|
|
1347
|
+
if(parsed.data !== undefined) {
|
|
1348
|
+
convertedValue = parsed.data;
|
|
1349
|
+
} else {
|
|
1350
|
+
convertedValue = parsed;
|
|
1351
|
+
}
|
|
1352
|
+
} catch (e) {
|
|
1353
|
+
// If literal parsing fails, just use the value as-is (don't bail)
|
|
1354
|
+
convertedValue = target;
|
|
1355
|
+
}
|
|
1356
|
+
} else if (typeof target === 'string') {
|
|
1357
|
+
// Type conversion: check the instance property's current type
|
|
1358
|
+
const expectedType = typeof instance[propName];
|
|
1359
|
+
if (expectedType === 'number') {
|
|
1360
|
+
convertedValue = Number(target);
|
|
1361
|
+
} else if (expectedType === 'boolean') {
|
|
1362
|
+
convertedValue = target === 'true' || target === '1';
|
|
1363
|
+
}
|
|
1364
|
+
}
|
|
1365
|
+
}
|
|
1366
|
+
|
|
1367
|
+
// Apply transform function if it exists
|
|
1368
|
+
if (propMeta.transform && typeof propMeta.transform === 'function') {
|
|
1369
|
+
convertedValue = propMeta.transform(convertedValue);
|
|
1370
|
+
}
|
|
1371
|
+
|
|
1372
|
+
instance[propName] = convertedValue;
|
|
1373
|
+
}
|
|
1374
|
+
foundProperty = true;
|
|
1375
|
+
break;
|
|
1376
|
+
}
|
|
1377
|
+
}
|
|
1378
|
+
|
|
1379
|
+
// If not a property, check if it's a collection
|
|
1380
|
+
if (!foundProperty) {
|
|
1381
|
+
for (const [collName, collMeta] of Object.entries(metadata.collections)) {
|
|
1382
|
+
if (collMeta.predicate === predicate) {
|
|
1383
|
+
// For collections, accumulate all values with their timestamps and indices for sorting
|
|
1384
|
+
if (!instance[collName]) {
|
|
1385
|
+
instance[collName] = [];
|
|
1386
|
+
}
|
|
1387
|
+
// Initialize timestamp tracking array if not already done
|
|
1388
|
+
const timestampsKey = `__${collName}_timestamps`;
|
|
1389
|
+
const indicesKey = `__${collName}_indices`;
|
|
1390
|
+
if (!instance[timestampsKey]) {
|
|
1391
|
+
instance[timestampsKey] = [];
|
|
1392
|
+
}
|
|
1393
|
+
if (!instance[indicesKey]) {
|
|
1394
|
+
instance[indicesKey] = [];
|
|
1395
|
+
}
|
|
1396
|
+
if (!instance[collName].includes(target)) {
|
|
1397
|
+
instance[collName].push(target);
|
|
1398
|
+
instance[timestampsKey].push(link.timestamp || '');
|
|
1399
|
+
// Track original position in the links array for stable sorting
|
|
1400
|
+
instance[indicesKey].push(linkIndex);
|
|
1401
|
+
}
|
|
1402
|
+
break;
|
|
1403
|
+
}
|
|
1404
|
+
}
|
|
1405
|
+
}
|
|
1406
|
+
}
|
|
1407
|
+
|
|
1408
|
+
// Set author and timestamp from the most recent link
|
|
1409
|
+
if (latestAuthor && maxTimestamp) {
|
|
1410
|
+
instance.author = latestAuthor;
|
|
1411
|
+
// Convert timestamp to number (milliseconds) if it's an ISO string
|
|
1412
|
+
if (typeof maxTimestamp === 'string' && maxTimestamp.includes('T')) {
|
|
1413
|
+
instance.timestamp = new Date(maxTimestamp).getTime();
|
|
1414
|
+
} else if (typeof maxTimestamp === 'string') {
|
|
1415
|
+
// Try to parse as number string
|
|
1416
|
+
const parsed = parseInt(maxTimestamp, 10);
|
|
1417
|
+
instance.timestamp = isNaN(parsed) ? maxTimestamp : parsed;
|
|
1418
|
+
} else {
|
|
1419
|
+
instance.timestamp = maxTimestamp;
|
|
1420
|
+
}
|
|
1421
|
+
}
|
|
1422
|
+
|
|
1423
|
+
// Sort collections by timestamp to maintain insertion order
|
|
1424
|
+
for (const [collName, collMeta] of Object.entries(metadata.collections)) {
|
|
1425
|
+
const timestampsKey = `__${collName}_timestamps`;
|
|
1426
|
+
const indicesKey = `__${collName}_indices`;
|
|
1427
|
+
if (instance[collName] && instance[timestampsKey]) {
|
|
1428
|
+
// Create array of [value, timestamp, index] tuples
|
|
1429
|
+
const pairs = instance[collName].map((value: any, index: number) => ({
|
|
1430
|
+
value,
|
|
1431
|
+
timestamp: instance[timestampsKey][index] || '',
|
|
1432
|
+
originalIndex: instance[indicesKey]?.[index] ?? index
|
|
1433
|
+
}));
|
|
1434
|
+
// Sort by timestamp first, then by original index for stable sorting
|
|
1435
|
+
pairs.sort((a, b) => {
|
|
1436
|
+
const tsA = String(a.timestamp || '');
|
|
1437
|
+
const tsB = String(b.timestamp || '');
|
|
1438
|
+
const tsCompare = tsA.localeCompare(tsB);
|
|
1439
|
+
if (tsCompare !== 0) return tsCompare;
|
|
1440
|
+
// Use original index as tiebreaker for stable sorting
|
|
1441
|
+
return a.originalIndex - b.originalIndex;
|
|
1442
|
+
});
|
|
1443
|
+
// Replace collection with sorted values
|
|
1444
|
+
instance[collName] = pairs.map(p => p.value);
|
|
1445
|
+
// Clean up temporary arrays
|
|
1446
|
+
delete instance[timestampsKey];
|
|
1447
|
+
delete instance[indicesKey];
|
|
1448
|
+
}
|
|
1449
|
+
}
|
|
1450
|
+
|
|
1451
|
+
// Filter by requested attributes if specified
|
|
1452
|
+
if (requestedProperties.length > 0 || requestedCollections.length > 0) {
|
|
1453
|
+
const requestedAttributes = [...requestedProperties, ...requestedCollections];
|
|
1454
|
+
Object.keys(instance).forEach((key) => {
|
|
1455
|
+
// Keep only requested attributes, plus always keep timestamp and author
|
|
1456
|
+
if (!requestedAttributes.includes(key) && key !== 'timestamp' && key !== 'author' && key !== 'baseExpression') {
|
|
1457
|
+
delete instance[key];
|
|
1458
|
+
}
|
|
1459
|
+
});
|
|
1460
|
+
}
|
|
1461
|
+
|
|
1462
|
+
instances.push(instance);
|
|
1463
|
+
} catch (error) {
|
|
1464
|
+
console.error(`Failed to process SurrealDB instance ${base}:`, error);
|
|
1465
|
+
}
|
|
1466
|
+
}
|
|
1467
|
+
|
|
1468
|
+
// Filter by where conditions that couldn't be filtered in SQL
|
|
1469
|
+
// This includes:
|
|
1470
|
+
// - author/timestamp (computed from grouped links)
|
|
1471
|
+
// - Properties with comparison operators (gt, gte, lt, lte, between, contains)
|
|
1472
|
+
// because fn::parse_literal() comparisons in SurrealDB subqueries don't work reliably
|
|
1473
|
+
let filteredInstances = instances;
|
|
1474
|
+
if (query.where) {
|
|
1475
|
+
filteredInstances = instances.filter(instance => {
|
|
1476
|
+
for (const [propertyName, condition] of Object.entries(query.where!)) {
|
|
1477
|
+
// Skip 'base' as it's filtered in SQL
|
|
1478
|
+
if (propertyName === 'base') continue;
|
|
1479
|
+
|
|
1480
|
+
// For author and timestamp, always filter in JS
|
|
1481
|
+
if (propertyName === 'author' || propertyName === 'timestamp') {
|
|
1482
|
+
if (!this.matchesCondition(instance[propertyName], condition)) {
|
|
1483
|
+
return false;
|
|
1484
|
+
}
|
|
1485
|
+
continue;
|
|
1486
|
+
}
|
|
1487
|
+
|
|
1488
|
+
// For regular properties, only filter comparison operators in JS
|
|
1489
|
+
// Simple equality and NOT are handled in SQL, but gt/gte/lt/lte/between/contains need JS
|
|
1490
|
+
if (typeof condition === 'object' && condition !== null && !Array.isArray(condition)) {
|
|
1491
|
+
const ops = condition as any;
|
|
1492
|
+
// Check if any comparison operators are present
|
|
1493
|
+
const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
|
|
1494
|
+
ops.lt !== undefined || ops.lte !== undefined ||
|
|
1495
|
+
ops.between !== undefined || ops.contains !== undefined;
|
|
1496
|
+
if (hasComparisonOps) {
|
|
1497
|
+
if (!this.matchesCondition(instance[propertyName], condition)) {
|
|
1498
|
+
return false;
|
|
1499
|
+
}
|
|
1500
|
+
}
|
|
1501
|
+
}
|
|
1502
|
+
}
|
|
1503
|
+
return true;
|
|
1504
|
+
});
|
|
1505
|
+
}
|
|
1506
|
+
|
|
1507
|
+
// Apply ordering in JavaScript
|
|
1508
|
+
// If limit/offset is used but no explicit order, default to ordering by timestamp (ASC)
|
|
1509
|
+
// This ensures consistent pagination behavior
|
|
1510
|
+
const effectiveOrder = query.order ||
|
|
1511
|
+
(query.limit !== undefined || query.offset !== undefined ? { timestamp: 'ASC' as 'ASC' } : null);
|
|
1512
|
+
|
|
1513
|
+
if (effectiveOrder) {
|
|
1514
|
+
const orderPropName = Object.keys(effectiveOrder)[0];
|
|
1515
|
+
const orderDirection = Object.values(effectiveOrder)[0];
|
|
1516
|
+
|
|
1517
|
+
filteredInstances.sort((a: any, b: any) => {
|
|
1518
|
+
let aVal = a[orderPropName];
|
|
1519
|
+
let bVal = b[orderPropName];
|
|
1520
|
+
|
|
1521
|
+
// Handle undefined values - push them to the end
|
|
1522
|
+
if (aVal === undefined && bVal === undefined) return 0;
|
|
1523
|
+
if (aVal === undefined) return orderDirection === 'ASC' ? 1 : -1;
|
|
1524
|
+
if (bVal === undefined) return orderDirection === 'ASC' ? -1 : 1;
|
|
1525
|
+
|
|
1526
|
+
// Compare values
|
|
1527
|
+
let comparison = 0;
|
|
1528
|
+
if (typeof aVal === 'number' && typeof bVal === 'number') {
|
|
1529
|
+
comparison = aVal - bVal;
|
|
1530
|
+
} else if (typeof aVal === 'string' && typeof bVal === 'string') {
|
|
1531
|
+
comparison = aVal.localeCompare(bVal);
|
|
1532
|
+
} else {
|
|
1533
|
+
// Convert to strings for comparison
|
|
1534
|
+
comparison = String(aVal).localeCompare(String(bVal));
|
|
1535
|
+
}
|
|
1536
|
+
|
|
1537
|
+
return orderDirection === 'DESC' ? -comparison : comparison;
|
|
1538
|
+
});
|
|
1539
|
+
}
|
|
1540
|
+
|
|
1541
|
+
// Calculate totalCount BEFORE applying limit/offset
|
|
1542
|
+
const totalCount = filteredInstances.length;
|
|
1543
|
+
|
|
1544
|
+
// Apply offset and limit in JavaScript
|
|
1545
|
+
let paginatedInstances = filteredInstances;
|
|
1546
|
+
if (query.offset !== undefined || query.limit !== undefined) {
|
|
1547
|
+
const start = query.offset || 0;
|
|
1548
|
+
const end = query.limit ? start + query.limit : undefined;
|
|
1549
|
+
paginatedInstances = filteredInstances.slice(start, end);
|
|
1550
|
+
}
|
|
1551
|
+
|
|
1552
|
+
return {
|
|
1553
|
+
results: paginatedInstances,
|
|
1554
|
+
totalCount
|
|
1555
|
+
};
|
|
1556
|
+
}
|
|
1557
|
+
|
|
1558
|
+
/**
|
|
1559
|
+
* Checks if a value matches a condition (for post-query filtering).
|
|
1560
|
+
* @private
|
|
1561
|
+
*/
|
|
1562
|
+
private static matchesCondition(value: any, condition: WhereCondition): boolean {
|
|
1563
|
+
// Handle array values (IN clause)
|
|
1564
|
+
if (Array.isArray(condition)) {
|
|
1565
|
+
return (condition as any[]).includes(value);
|
|
1566
|
+
}
|
|
1567
|
+
|
|
1568
|
+
// Handle operator object
|
|
1569
|
+
if (typeof condition === 'object' && condition !== null) {
|
|
1570
|
+
const ops = condition as any;
|
|
1571
|
+
|
|
1572
|
+
// Special case: 'not' operator (exclusive with other operators)
|
|
1573
|
+
if (ops.not !== undefined) {
|
|
1574
|
+
if (Array.isArray(ops.not)) {
|
|
1575
|
+
return !(ops.not as any[]).includes(value);
|
|
1576
|
+
} else {
|
|
1577
|
+
return value !== ops.not;
|
|
1578
|
+
}
|
|
1579
|
+
}
|
|
1580
|
+
|
|
1581
|
+
// Special case: 'between' operator (inclusive range, exclusive with gt/gte/lt/lte)
|
|
1582
|
+
if (ops.between !== undefined && Array.isArray(ops.between) && ops.between.length === 2) {
|
|
1583
|
+
return value >= ops.between[0] && value <= ops.between[1];
|
|
1584
|
+
}
|
|
1585
|
+
|
|
1586
|
+
// For all other operators (gt, gte, lt, lte, contains), we need to check ALL of them
|
|
1587
|
+
// and return true only if ALL conditions are satisfied
|
|
1588
|
+
let allConditionsMet = true;
|
|
1589
|
+
|
|
1590
|
+
if (ops.gt !== undefined) {
|
|
1591
|
+
allConditionsMet = allConditionsMet && (value > ops.gt);
|
|
1592
|
+
}
|
|
1593
|
+
|
|
1594
|
+
if (ops.gte !== undefined) {
|
|
1595
|
+
allConditionsMet = allConditionsMet && (value >= ops.gte);
|
|
1596
|
+
}
|
|
1597
|
+
|
|
1598
|
+
if (ops.lt !== undefined) {
|
|
1599
|
+
allConditionsMet = allConditionsMet && (value < ops.lt);
|
|
1600
|
+
}
|
|
1601
|
+
|
|
1602
|
+
if (ops.lte !== undefined) {
|
|
1603
|
+
allConditionsMet = allConditionsMet && (value <= ops.lte);
|
|
1604
|
+
}
|
|
1605
|
+
|
|
1606
|
+
if (ops.contains !== undefined) {
|
|
1607
|
+
if (typeof value === 'string') {
|
|
1608
|
+
allConditionsMet = allConditionsMet && value.includes(String(ops.contains));
|
|
1609
|
+
} else if (Array.isArray(value)) {
|
|
1610
|
+
allConditionsMet = allConditionsMet && value.includes(ops.contains);
|
|
1611
|
+
} else {
|
|
1612
|
+
allConditionsMet = false;
|
|
1613
|
+
}
|
|
1614
|
+
}
|
|
1615
|
+
|
|
1616
|
+
return allConditionsMet;
|
|
1617
|
+
}
|
|
1618
|
+
|
|
1619
|
+
// Simple equality
|
|
1620
|
+
return value === condition;
|
|
1621
|
+
}
|
|
1622
|
+
|
|
480
1623
|
/**
|
|
481
1624
|
* Gets all instances of the model in the perspective that match the query params.
|
|
482
1625
|
*
|
|
483
1626
|
* @param perspective - The perspective to search in
|
|
484
1627
|
* @param query - Optional query parameters to filter results
|
|
1628
|
+
* @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
|
|
485
1629
|
* @returns Array of matching models
|
|
486
1630
|
*
|
|
487
1631
|
* @example
|
|
488
1632
|
* ```typescript
|
|
489
|
-
* // Get all recipes
|
|
1633
|
+
* // Get all recipes (uses SurrealDB by default)
|
|
490
1634
|
* const allRecipes = await Recipe.findAll(perspective);
|
|
491
1635
|
*
|
|
492
|
-
* // Get recipes with specific criteria
|
|
1636
|
+
* // Get recipes with specific criteria (uses SurrealDB)
|
|
493
1637
|
* const recipes = await Recipe.findAll(perspective, {
|
|
494
1638
|
* where: {
|
|
495
1639
|
* name: "Pasta",
|
|
@@ -498,17 +1642,28 @@ export class Ad4mModel {
|
|
|
498
1642
|
* order: { createdAt: "DESC" },
|
|
499
1643
|
* limit: 10
|
|
500
1644
|
* });
|
|
1645
|
+
*
|
|
1646
|
+
* // Explicitly use Prolog (legacy, for backward compatibility)
|
|
1647
|
+
* const recipesProlog = await Recipe.findAll(perspective, {}, false);
|
|
501
1648
|
* ```
|
|
502
1649
|
*/
|
|
503
1650
|
static async findAll<T extends Ad4mModel>(
|
|
504
1651
|
this: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
505
1652
|
perspective: PerspectiveProxy,
|
|
506
|
-
query: Query = {}
|
|
1653
|
+
query: Query = {},
|
|
1654
|
+
useSurrealDB: boolean = true
|
|
507
1655
|
): Promise<T[]> {
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
1656
|
+
if (useSurrealDB) {
|
|
1657
|
+
const surrealQuery = await this.queryToSurrealQL(perspective, query);
|
|
1658
|
+
const result = await perspective.querySurrealDB(surrealQuery);
|
|
1659
|
+
const { results } = await this.instancesFromSurrealResult(perspective, query, result);
|
|
1660
|
+
return results;
|
|
1661
|
+
} else {
|
|
1662
|
+
const prologQuery = await this.queryToProlog(perspective, query);
|
|
1663
|
+
const result = await perspective.infer(prologQuery);
|
|
1664
|
+
const { results } = await this.instancesFromPrologResult(perspective, query, result);
|
|
1665
|
+
return results;
|
|
1666
|
+
}
|
|
512
1667
|
}
|
|
513
1668
|
|
|
514
1669
|
/**
|
|
@@ -516,6 +1671,7 @@ export class Ad4mModel {
|
|
|
516
1671
|
*
|
|
517
1672
|
* @param perspective - The perspective to search in
|
|
518
1673
|
* @param query - Optional query parameters to filter results
|
|
1674
|
+
* @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
|
|
519
1675
|
* @returns Object containing results array and total count
|
|
520
1676
|
*
|
|
521
1677
|
* @example
|
|
@@ -525,16 +1681,26 @@ export class Ad4mModel {
|
|
|
525
1681
|
* limit: 10
|
|
526
1682
|
* });
|
|
527
1683
|
* console.log(`Showing 10 of ${totalCount} dessert recipes`);
|
|
1684
|
+
*
|
|
1685
|
+
* // Use Prolog explicitly (legacy)
|
|
1686
|
+
* const { results, totalCount } = await Recipe.findAllAndCount(perspective, {}, false);
|
|
528
1687
|
* ```
|
|
529
1688
|
*/
|
|
530
1689
|
static async findAllAndCount<T extends Ad4mModel>(
|
|
531
1690
|
this: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
532
1691
|
perspective: PerspectiveProxy,
|
|
533
|
-
query: Query = {}
|
|
1692
|
+
query: Query = {},
|
|
1693
|
+
useSurrealDB: boolean = true
|
|
534
1694
|
): Promise<ResultsWithTotalCount<T>> {
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
1695
|
+
if (useSurrealDB) {
|
|
1696
|
+
const surrealQuery = await this.queryToSurrealQL(perspective, query);
|
|
1697
|
+
const result = await perspective.querySurrealDB(surrealQuery);
|
|
1698
|
+
return await this.instancesFromSurrealResult(perspective, query, result);
|
|
1699
|
+
} else {
|
|
1700
|
+
const prologQuery = await this.queryToProlog(perspective, query);
|
|
1701
|
+
const result = await perspective.infer(prologQuery);
|
|
1702
|
+
return await this.instancesFromPrologResult(perspective, query, result);
|
|
1703
|
+
}
|
|
538
1704
|
}
|
|
539
1705
|
|
|
540
1706
|
/**
|
|
@@ -544,6 +1710,7 @@ export class Ad4mModel {
|
|
|
544
1710
|
* @param pageSize - Number of items per page
|
|
545
1711
|
* @param pageNumber - Which page to retrieve (1-based)
|
|
546
1712
|
* @param query - Optional additional query parameters
|
|
1713
|
+
* @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
|
|
547
1714
|
* @returns Paginated results with metadata
|
|
548
1715
|
*
|
|
549
1716
|
* @example
|
|
@@ -552,6 +1719,9 @@ export class Ad4mModel {
|
|
|
552
1719
|
* where: { category: "Main Course" }
|
|
553
1720
|
* });
|
|
554
1721
|
* console.log(`Page ${page.pageNumber} of recipes, ${page.results.length} items`);
|
|
1722
|
+
*
|
|
1723
|
+
* // Use Prolog explicitly (legacy)
|
|
1724
|
+
* const pageProlog = await Recipe.paginate(perspective, 10, 1, {}, false);
|
|
555
1725
|
* ```
|
|
556
1726
|
*/
|
|
557
1727
|
static async paginate<T extends Ad4mModel>(
|
|
@@ -559,13 +1729,21 @@ export class Ad4mModel {
|
|
|
559
1729
|
perspective: PerspectiveProxy,
|
|
560
1730
|
pageSize: number,
|
|
561
1731
|
pageNumber: number,
|
|
562
|
-
query?: Query
|
|
1732
|
+
query?: Query,
|
|
1733
|
+
useSurrealDB: boolean = true
|
|
563
1734
|
): Promise<PaginationResult<T>> {
|
|
564
1735
|
const paginationQuery = { ...(query || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
1736
|
+
if (useSurrealDB) {
|
|
1737
|
+
const surrealQuery = await this.queryToSurrealQL(perspective, paginationQuery);
|
|
1738
|
+
const result = await perspective.querySurrealDB(surrealQuery);
|
|
1739
|
+
const { results, totalCount } = await this.instancesFromSurrealResult(perspective, paginationQuery, result);
|
|
1740
|
+
return { results, totalCount, pageSize, pageNumber };
|
|
1741
|
+
} else {
|
|
1742
|
+
const prologQuery = await this.queryToProlog(perspective, paginationQuery);
|
|
1743
|
+
const result = await perspective.infer(prologQuery);
|
|
1744
|
+
const { results, totalCount } = await this.instancesFromPrologResult(perspective, paginationQuery, result);
|
|
1745
|
+
return { results, totalCount, pageSize, pageNumber };
|
|
1746
|
+
}
|
|
569
1747
|
}
|
|
570
1748
|
|
|
571
1749
|
static async countQueryToProlog(perspective: PerspectiveProxy, query: Query = {}, modelClassName?: string | null) {
|
|
@@ -586,11 +1764,30 @@ export class Ad4mModel {
|
|
|
586
1764
|
return fullQuery;
|
|
587
1765
|
}
|
|
588
1766
|
|
|
1767
|
+
/**
|
|
1768
|
+
* Generates a SurrealQL COUNT query for the model.
|
|
1769
|
+
*
|
|
1770
|
+
* @param perspective - The perspective context
|
|
1771
|
+
* @param query - Query parameters to filter the count
|
|
1772
|
+
* @returns SurrealQL COUNT query string
|
|
1773
|
+
*
|
|
1774
|
+
* @private
|
|
1775
|
+
*/
|
|
1776
|
+
public static async countQueryToSurrealQL(perspective: PerspectiveProxy, query: Query): Promise<string> {
|
|
1777
|
+
// Use the same query as the main query (with GROUP BY), just without LIMIT/OFFSET
|
|
1778
|
+
// We'll count the number of rows returned (one row per source)
|
|
1779
|
+
const countQuery = { ...query };
|
|
1780
|
+
delete countQuery.limit;
|
|
1781
|
+
delete countQuery.offset;
|
|
1782
|
+
return await this.queryToSurrealQL(perspective, countQuery);
|
|
1783
|
+
}
|
|
1784
|
+
|
|
589
1785
|
/**
|
|
590
1786
|
* Gets a count of all matching instances.
|
|
591
1787
|
*
|
|
592
1788
|
* @param perspective - The perspective to search in
|
|
593
1789
|
* @param query - Optional query parameters to filter results
|
|
1790
|
+
* @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
|
|
594
1791
|
* @returns Total count of matching entities
|
|
595
1792
|
*
|
|
596
1793
|
* @example
|
|
@@ -599,12 +1796,24 @@ export class Ad4mModel {
|
|
|
599
1796
|
* const activeRecipes = await Recipe.count(perspective, {
|
|
600
1797
|
* where: { status: "active" }
|
|
601
1798
|
* });
|
|
1799
|
+
*
|
|
1800
|
+
* // Use Prolog explicitly (legacy)
|
|
1801
|
+
* const countProlog = await Recipe.count(perspective, {}, false);
|
|
602
1802
|
* ```
|
|
603
1803
|
*/
|
|
604
|
-
static async count(perspective: PerspectiveProxy, query: Query = {}) {
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
1804
|
+
static async count(perspective: PerspectiveProxy, query: Query = {}, useSurrealDB: boolean = true) {
|
|
1805
|
+
if (useSurrealDB) {
|
|
1806
|
+
const surrealQuery = await this.queryToSurrealQL(perspective, query);
|
|
1807
|
+
const result = await perspective.querySurrealDB(surrealQuery);
|
|
1808
|
+
// Use instancesFromSurrealResult to apply JS-level filtering for advanced where conditions
|
|
1809
|
+
// (e.g., gt, gte, lt, lte, between, contains on properties and author/timestamp)
|
|
1810
|
+
// This ensures count() returns the same number as findAll().length
|
|
1811
|
+
const { totalCount } = await this.instancesFromSurrealResult(perspective, query, result);
|
|
1812
|
+
return totalCount;
|
|
1813
|
+
} else {
|
|
1814
|
+
const result = await perspective.infer(await this.countQueryToProlog(perspective, query));
|
|
1815
|
+
return result?.[0]?.TotalCount || 0;
|
|
1816
|
+
}
|
|
608
1817
|
}
|
|
609
1818
|
|
|
610
1819
|
private async setProperty(key: string, value: any, batchId?: string) {
|
|
@@ -899,6 +2108,368 @@ export class Ad4mModel {
|
|
|
899
2108
|
): ModelQueryBuilder<T> {
|
|
900
2109
|
return new ModelQueryBuilder<T>(perspective, this as any, query);
|
|
901
2110
|
}
|
|
2111
|
+
|
|
2112
|
+
/**
|
|
2113
|
+
* Creates an Ad4mModel class from a JSON Schema definition.
|
|
2114
|
+
*
|
|
2115
|
+
* @description
|
|
2116
|
+
* This method dynamically generates an Ad4mModel subclass from a JSON Schema,
|
|
2117
|
+
* enabling integration with systems that use JSON Schema for type definitions.
|
|
2118
|
+
*
|
|
2119
|
+
* The method follows a cascading approach for determining predicates:
|
|
2120
|
+
* 1. Explicit configuration in options parameter (highest precedence)
|
|
2121
|
+
* 2. x-ad4m metadata in the JSON Schema
|
|
2122
|
+
* 3. Inference from schema title and property names
|
|
2123
|
+
* 4. Error if no namespace can be determined
|
|
2124
|
+
*
|
|
2125
|
+
* @example
|
|
2126
|
+
* ```typescript
|
|
2127
|
+
* // With explicit configuration
|
|
2128
|
+
* const PersonClass = Ad4mModel.fromJSONSchema(schema, {
|
|
2129
|
+
* name: "Person",
|
|
2130
|
+
* namespace: "person://",
|
|
2131
|
+
* resolveLanguage: "literal"
|
|
2132
|
+
* });
|
|
2133
|
+
*
|
|
2134
|
+
* // With property mapping
|
|
2135
|
+
* const ContactClass = Ad4mModel.fromJSONSchema(schema, {
|
|
2136
|
+
* name: "Contact",
|
|
2137
|
+
* namespace: "contact://",
|
|
2138
|
+
* propertyMapping: {
|
|
2139
|
+
* "name": "foaf://name",
|
|
2140
|
+
* "email": "foaf://mbox"
|
|
2141
|
+
* }
|
|
2142
|
+
* });
|
|
2143
|
+
*
|
|
2144
|
+
* // With x-ad4m metadata in schema
|
|
2145
|
+
* const schema = {
|
|
2146
|
+
* "title": "Product",
|
|
2147
|
+
* "x-ad4m": { "namespace": "product://" },
|
|
2148
|
+
* "properties": {
|
|
2149
|
+
* "name": {
|
|
2150
|
+
* "type": "string",
|
|
2151
|
+
* "x-ad4m": { "through": "product://title" }
|
|
2152
|
+
* }
|
|
2153
|
+
* }
|
|
2154
|
+
* };
|
|
2155
|
+
* const ProductClass = Ad4mModel.fromJSONSchema(schema, { name: "Product" });
|
|
2156
|
+
* ```
|
|
2157
|
+
*
|
|
2158
|
+
* @param schema - JSON Schema definition
|
|
2159
|
+
* @param options - Configuration options
|
|
2160
|
+
* @returns Generated Ad4mModel subclass
|
|
2161
|
+
* @throws Error when namespace cannot be inferred
|
|
2162
|
+
*/
|
|
2163
|
+
static fromJSONSchema(
|
|
2164
|
+
schema: JSONSchema,
|
|
2165
|
+
options: JSONSchemaToModelOptions
|
|
2166
|
+
): typeof Ad4mModel {
|
|
2167
|
+
// Disallow top-level "author" property since Ad4mModel provides it implicitly via link authorship
|
|
2168
|
+
if (schema?.properties && Object.prototype.hasOwnProperty.call(schema.properties, "author")) {
|
|
2169
|
+
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").');
|
|
2170
|
+
}
|
|
2171
|
+
// Determine namespace with cascading precedence
|
|
2172
|
+
const namespace = this.determineNamespace(schema, options);
|
|
2173
|
+
|
|
2174
|
+
// Create the dynamic class
|
|
2175
|
+
const DynamicModelClass = class extends Ad4mModel {};
|
|
2176
|
+
|
|
2177
|
+
// Set up class metadata
|
|
2178
|
+
if (!options.name || options.name.trim() === '') {
|
|
2179
|
+
throw new Error("options.name is required and cannot be empty");
|
|
2180
|
+
}
|
|
2181
|
+
(DynamicModelClass as any).className = options.name;
|
|
2182
|
+
(DynamicModelClass.prototype as any).className = options.name;
|
|
2183
|
+
|
|
2184
|
+
// Generate properties and collections metadata
|
|
2185
|
+
const properties: any = {};
|
|
2186
|
+
const collections: any = {};
|
|
2187
|
+
|
|
2188
|
+
if (schema.properties) {
|
|
2189
|
+
for (const [propertyName, propertySchema] of Object.entries(schema.properties)) {
|
|
2190
|
+
const predicate = this.determinePredicate(schema, propertyName, propertySchema, namespace, options);
|
|
2191
|
+
const isRequired = schema.required?.includes(propertyName) || false;
|
|
2192
|
+
const propertyType = normalizeSchemaType(propertySchema.type);
|
|
2193
|
+
const isArray = isArrayType(propertySchema);
|
|
2194
|
+
|
|
2195
|
+
if (isArray) {
|
|
2196
|
+
// Handle arrays as collections
|
|
2197
|
+
// Store the singular form as the collection key since SDNA generation expects singular
|
|
2198
|
+
collections[propertyName] = {
|
|
2199
|
+
through: predicate,
|
|
2200
|
+
local: this.getPropertyOption(propertyName, propertySchema, options, 'local')
|
|
2201
|
+
};
|
|
2202
|
+
|
|
2203
|
+
// Define the property on prototype
|
|
2204
|
+
Object.defineProperty(DynamicModelClass.prototype, propertyName, {
|
|
2205
|
+
configurable: true,
|
|
2206
|
+
writable: true,
|
|
2207
|
+
value: []
|
|
2208
|
+
});
|
|
2209
|
+
|
|
2210
|
+
// Add collection methods
|
|
2211
|
+
const adderName = `add${capitalize(propertyName)}`;
|
|
2212
|
+
const removerName = `remove${capitalize(propertyName)}`;
|
|
2213
|
+
const setterName = `setCollection${capitalize(propertyName)}`;
|
|
2214
|
+
|
|
2215
|
+
(DynamicModelClass.prototype as any)[adderName] = function() {
|
|
2216
|
+
// Placeholder function for SDNA generation
|
|
2217
|
+
};
|
|
2218
|
+
(DynamicModelClass.prototype as any)[removerName] = function() {
|
|
2219
|
+
// Placeholder function for SDNA generation
|
|
2220
|
+
};
|
|
2221
|
+
(DynamicModelClass.prototype as any)[setterName] = function() {
|
|
2222
|
+
// Placeholder function for SDNA generation
|
|
2223
|
+
};
|
|
2224
|
+
|
|
2225
|
+
} else {
|
|
2226
|
+
// Handle regular properties
|
|
2227
|
+
let resolveLanguage = this.getPropertyOption(propertyName, propertySchema, options, 'resolveLanguage');
|
|
2228
|
+
// If no specific resolveLanguage for this property, use the global one
|
|
2229
|
+
if (!resolveLanguage && options.resolveLanguage) {
|
|
2230
|
+
resolveLanguage = options.resolveLanguage;
|
|
2231
|
+
}
|
|
2232
|
+
const local = this.getPropertyOption(propertyName, propertySchema, options, 'local');
|
|
2233
|
+
const writable = this.getPropertyOption(propertyName, propertySchema, options, 'writable', true);
|
|
2234
|
+
let initial = this.getPropertyOption(propertyName, propertySchema, options, 'initial');
|
|
2235
|
+
|
|
2236
|
+
// Handle nested objects by serializing to JSON
|
|
2237
|
+
if (isObjectType(propertySchema) && !resolveLanguage) {
|
|
2238
|
+
resolveLanguage = 'literal';
|
|
2239
|
+
console.warn(`Property "${propertyName}" is an object type. It will be stored as JSON. Consider flattening complex objects for better semantic querying.`);
|
|
2240
|
+
}
|
|
2241
|
+
|
|
2242
|
+
// Ensure numeric properties use literal language for correct typing
|
|
2243
|
+
if ((resolveLanguage === undefined || resolveLanguage === null) && isNumericType(propertySchema)) {
|
|
2244
|
+
resolveLanguage = 'literal';
|
|
2245
|
+
}
|
|
2246
|
+
|
|
2247
|
+
// If property is required, ensure it has an initial value
|
|
2248
|
+
if (isRequired && !initial) {
|
|
2249
|
+
if (isObjectType(propertySchema)) {
|
|
2250
|
+
initial = 'literal://json:{}';
|
|
2251
|
+
} else {
|
|
2252
|
+
initial = "ad4m://undefined";
|
|
2253
|
+
}
|
|
2254
|
+
}
|
|
2255
|
+
|
|
2256
|
+
properties[propertyName] = {
|
|
2257
|
+
through: predicate,
|
|
2258
|
+
required: isRequired,
|
|
2259
|
+
writable: writable,
|
|
2260
|
+
...(resolveLanguage && { resolveLanguage }),
|
|
2261
|
+
...(local !== undefined && { local }),
|
|
2262
|
+
...(initial && { initial })
|
|
2263
|
+
};
|
|
2264
|
+
|
|
2265
|
+
// Define the property on prototype
|
|
2266
|
+
Object.defineProperty(DynamicModelClass.prototype, propertyName, {
|
|
2267
|
+
configurable: true,
|
|
2268
|
+
writable: true,
|
|
2269
|
+
value: this.getDefaultValueForType(propertyType)
|
|
2270
|
+
});
|
|
2271
|
+
|
|
2272
|
+
// Add setter function if writable
|
|
2273
|
+
if (writable) {
|
|
2274
|
+
const setterName = propertyNameToSetterName(propertyName);
|
|
2275
|
+
(DynamicModelClass.prototype as any)[setterName] = function() {
|
|
2276
|
+
// This is a placeholder function that the SDNA generation looks for
|
|
2277
|
+
// The actual setter logic is handled by the Ad4mModel base class
|
|
2278
|
+
};
|
|
2279
|
+
}
|
|
2280
|
+
}
|
|
2281
|
+
}
|
|
2282
|
+
}
|
|
2283
|
+
|
|
2284
|
+
// Validate that at least one property has an initial value (needed for valid SDNA constructor)
|
|
2285
|
+
// Collections don't create constructor actions, only properties with initial values do
|
|
2286
|
+
const hasPropertyWithInitial = Object.values(properties).some((prop: any) => prop.initial);
|
|
2287
|
+
|
|
2288
|
+
if (!hasPropertyWithInitial) {
|
|
2289
|
+
// If no properties have initial values, add a type identifier automatically
|
|
2290
|
+
const typeProperty = `ad4m://type`;
|
|
2291
|
+
let typeValue: string;
|
|
2292
|
+
if (namespace.includes('://')) {
|
|
2293
|
+
const [scheme, rest] = namespace.split('://');
|
|
2294
|
+
const path = (rest || '').replace(/\/+$/,'');
|
|
2295
|
+
if (path) {
|
|
2296
|
+
typeValue = `${scheme}://${path}/instance`;
|
|
2297
|
+
} else {
|
|
2298
|
+
typeValue = `${scheme}://instance`;
|
|
2299
|
+
}
|
|
2300
|
+
} else {
|
|
2301
|
+
const path = namespace.replace(/\/+$/,'');
|
|
2302
|
+
typeValue = `${path}/instance`;
|
|
2303
|
+
}
|
|
2304
|
+
|
|
2305
|
+
properties['__ad4m_type'] = {
|
|
2306
|
+
through: typeProperty,
|
|
2307
|
+
required: true,
|
|
2308
|
+
writable: false,
|
|
2309
|
+
initial: typeValue,
|
|
2310
|
+
flag: true
|
|
2311
|
+
};
|
|
2312
|
+
|
|
2313
|
+
// Add the type property to the prototype
|
|
2314
|
+
Object.defineProperty(DynamicModelClass.prototype, '__ad4m_type', {
|
|
2315
|
+
configurable: true,
|
|
2316
|
+
writable: false,
|
|
2317
|
+
value: typeValue
|
|
2318
|
+
});
|
|
2319
|
+
|
|
2320
|
+
console.warn(`No properties with initial values found. Added automatic type flag: ${typeProperty} = ${typeValue}`);
|
|
2321
|
+
}
|
|
2322
|
+
|
|
2323
|
+
// Attach metadata to prototype
|
|
2324
|
+
(DynamicModelClass.prototype as any).__properties = properties;
|
|
2325
|
+
(DynamicModelClass.prototype as any).__collections = collections;
|
|
2326
|
+
|
|
2327
|
+
// Store the JSON schema and options on the prototype for potential fallback use by getModelMetadata()
|
|
2328
|
+
(DynamicModelClass.prototype as any).__jsonSchema = schema;
|
|
2329
|
+
(DynamicModelClass.prototype as any).__jsonSchemaOptions = options;
|
|
2330
|
+
|
|
2331
|
+
// Apply the ModelOptions decorator to set up the generateSDNA method
|
|
2332
|
+
const ModelOptionsDecorator = ModelOptions({ name: options.name });
|
|
2333
|
+
ModelOptionsDecorator(DynamicModelClass);
|
|
2334
|
+
|
|
2335
|
+
return DynamicModelClass as typeof Ad4mModel;
|
|
2336
|
+
}
|
|
2337
|
+
|
|
2338
|
+
/**
|
|
2339
|
+
* Determines the namespace for predicates using cascading precedence
|
|
2340
|
+
*/
|
|
2341
|
+
private static determineNamespace(schema: JSONSchema, options: JSONSchemaToModelOptions): string {
|
|
2342
|
+
// 1. Explicit namespace in options (highest precedence)
|
|
2343
|
+
if (options.namespace) {
|
|
2344
|
+
return options.namespace;
|
|
2345
|
+
}
|
|
2346
|
+
|
|
2347
|
+
// 2. x-ad4m metadata in schema
|
|
2348
|
+
if (schema["x-ad4m"]?.namespace) {
|
|
2349
|
+
return schema["x-ad4m"].namespace;
|
|
2350
|
+
}
|
|
2351
|
+
|
|
2352
|
+
// 3. Infer from schema title
|
|
2353
|
+
if (schema.title) {
|
|
2354
|
+
return `${schema.title.toLowerCase()}://`;
|
|
2355
|
+
}
|
|
2356
|
+
|
|
2357
|
+
// 4. Try to extract from $id if it's a URL
|
|
2358
|
+
if (schema.$id) {
|
|
2359
|
+
try {
|
|
2360
|
+
const url = new URL(schema.$id);
|
|
2361
|
+
const pathParts = url.pathname.split('/').filter(p => p);
|
|
2362
|
+
if (pathParts.length > 0) {
|
|
2363
|
+
const lastPart = pathParts[pathParts.length - 1];
|
|
2364
|
+
const baseName = lastPart.replace(/\.schema\.json$/, '').replace(/\.json$/, '');
|
|
2365
|
+
return `${baseName.toLowerCase()}://`;
|
|
2366
|
+
}
|
|
2367
|
+
} catch {
|
|
2368
|
+
// If $id is not a valid URL, continue to error
|
|
2369
|
+
}
|
|
2370
|
+
}
|
|
2371
|
+
|
|
2372
|
+
// 5. Error if no namespace can be determined
|
|
2373
|
+
throw new Error(
|
|
2374
|
+
`Cannot infer namespace for JSON Schema. Please provide one of:
|
|
2375
|
+
- options.namespace
|
|
2376
|
+
- schema["x-ad4m"].namespace
|
|
2377
|
+
- schema.title
|
|
2378
|
+
- valid schema.$id`
|
|
2379
|
+
);
|
|
2380
|
+
}
|
|
2381
|
+
|
|
2382
|
+
/**
|
|
2383
|
+
* Determines the predicate for a specific property using cascading precedence
|
|
2384
|
+
*/
|
|
2385
|
+
private static determinePredicate(
|
|
2386
|
+
schema: JSONSchema,
|
|
2387
|
+
propertyName: string,
|
|
2388
|
+
propertySchema: JSONSchemaProperty,
|
|
2389
|
+
namespace: string,
|
|
2390
|
+
options: JSONSchemaToModelOptions
|
|
2391
|
+
): string {
|
|
2392
|
+
// 1. Explicit property mapping (highest precedence)
|
|
2393
|
+
if (options.propertyMapping?.[propertyName]) {
|
|
2394
|
+
return options.propertyMapping[propertyName];
|
|
2395
|
+
}
|
|
2396
|
+
|
|
2397
|
+
// 2. x-ad4m metadata in property schema
|
|
2398
|
+
if (propertySchema["x-ad4m"]?.through) {
|
|
2399
|
+
return propertySchema["x-ad4m"].through;
|
|
2400
|
+
}
|
|
2401
|
+
|
|
2402
|
+
// 3. Generate from namespace + property name
|
|
2403
|
+
if (options.predicateTemplate) {
|
|
2404
|
+
const normalizedNs = normalizeNamespaceString(namespace);
|
|
2405
|
+
const [scheme, rest] = normalizedNs.includes('://') ? normalizedNs.split('://') : ['', normalizedNs];
|
|
2406
|
+
const nsNoScheme = rest || '';
|
|
2407
|
+
return options.predicateTemplate
|
|
2408
|
+
.replace('${namespace}', nsNoScheme)
|
|
2409
|
+
.replace('${scheme}', scheme)
|
|
2410
|
+
.replace('${ns}', nsNoScheme)
|
|
2411
|
+
.replace('${title}', schema.title || '')
|
|
2412
|
+
.replace('${property}', propertyName);
|
|
2413
|
+
}
|
|
2414
|
+
|
|
2415
|
+
// 4. Custom predicate generator
|
|
2416
|
+
if (options.predicateGenerator) {
|
|
2417
|
+
return options.predicateGenerator(schema.title || '', propertyName);
|
|
2418
|
+
}
|
|
2419
|
+
|
|
2420
|
+
// 5. Default: namespace + property name
|
|
2421
|
+
const normalizedNs = normalizeNamespaceString(namespace);
|
|
2422
|
+
if (normalizedNs.includes('://')) {
|
|
2423
|
+
// For namespaces like "product://", append property directly
|
|
2424
|
+
return `${normalizedNs}${propertyName}`;
|
|
2425
|
+
} else {
|
|
2426
|
+
return `${normalizedNs}://${propertyName}`;
|
|
2427
|
+
}
|
|
2428
|
+
}
|
|
2429
|
+
|
|
2430
|
+
/**
|
|
2431
|
+
* Gets property-specific options using cascading precedence
|
|
2432
|
+
*/
|
|
2433
|
+
private static getPropertyOption(
|
|
2434
|
+
propertyName: string,
|
|
2435
|
+
propertySchema: JSONSchemaProperty,
|
|
2436
|
+
options: JSONSchemaToModelOptions,
|
|
2437
|
+
optionName: keyof PropertyOptions,
|
|
2438
|
+
defaultValue?: any
|
|
2439
|
+
): any {
|
|
2440
|
+
// 1. Property-specific options
|
|
2441
|
+
if (options.propertyOptions?.[propertyName]?.[optionName] !== undefined) {
|
|
2442
|
+
return options.propertyOptions[propertyName][optionName];
|
|
2443
|
+
}
|
|
2444
|
+
|
|
2445
|
+
// 2. x-ad4m metadata in property
|
|
2446
|
+
if (propertySchema["x-ad4m"]?.[optionName as keyof JSONSchemaProperty["x-ad4m"]] !== undefined) {
|
|
2447
|
+
return propertySchema["x-ad4m"][optionName as keyof JSONSchemaProperty["x-ad4m"]];
|
|
2448
|
+
}
|
|
2449
|
+
|
|
2450
|
+
// 3. Global option
|
|
2451
|
+
if (options[optionName as keyof JSONSchemaToModelOptions] !== undefined) {
|
|
2452
|
+
return options[optionName as keyof JSONSchemaToModelOptions];
|
|
2453
|
+
}
|
|
2454
|
+
|
|
2455
|
+
// 4. Default value
|
|
2456
|
+
return defaultValue;
|
|
2457
|
+
}
|
|
2458
|
+
|
|
2459
|
+
/**
|
|
2460
|
+
* Gets default value for a JSON Schema type
|
|
2461
|
+
*/
|
|
2462
|
+
private static getDefaultValueForType(type?: string): any {
|
|
2463
|
+
switch (type) {
|
|
2464
|
+
case 'string': return '';
|
|
2465
|
+
case 'number': return 0;
|
|
2466
|
+
case 'integer': return 0;
|
|
2467
|
+
case 'boolean': return false;
|
|
2468
|
+
case 'array': return [];
|
|
2469
|
+
case 'object': return {};
|
|
2470
|
+
default: return '';
|
|
2471
|
+
}
|
|
2472
|
+
}
|
|
902
2473
|
}
|
|
903
2474
|
|
|
904
2475
|
/** Query builder for Ad4mModel queries.
|
|
@@ -927,6 +2498,7 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
|
|
|
927
2498
|
private modelClassName: string | null = null;
|
|
928
2499
|
private ctor: typeof Ad4mModel;
|
|
929
2500
|
private currentSubscription?: any;
|
|
2501
|
+
private useSurrealDBFlag: boolean = true;
|
|
930
2502
|
|
|
931
2503
|
constructor(perspective: PerspectiveProxy, ctor: typeof Ad4mModel, query?: Query) {
|
|
932
2504
|
this.perspective = perspective;
|
|
@@ -1075,6 +2647,36 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
|
|
|
1075
2647
|
return this;
|
|
1076
2648
|
}
|
|
1077
2649
|
|
|
2650
|
+
/**
|
|
2651
|
+
* Enables or disables SurrealDB query path.
|
|
2652
|
+
*
|
|
2653
|
+
* @param enabled - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
|
|
2654
|
+
* @returns The query builder for chaining
|
|
2655
|
+
*
|
|
2656
|
+
* @example
|
|
2657
|
+
* ```typescript
|
|
2658
|
+
* // Use SurrealDB (default)
|
|
2659
|
+
* const recipes = await Recipe.query(perspective)
|
|
2660
|
+
* .where({ category: "Dessert" })
|
|
2661
|
+
* .useSurrealDB(true)
|
|
2662
|
+
* .get();
|
|
2663
|
+
*
|
|
2664
|
+
* // Use Prolog (legacy)
|
|
2665
|
+
* const recipesProlog = await Recipe.query(perspective)
|
|
2666
|
+
* .where({ category: "Dessert" })
|
|
2667
|
+
* .useSurrealDB(false)
|
|
2668
|
+
* .get();
|
|
2669
|
+
* ```
|
|
2670
|
+
*
|
|
2671
|
+
* @remarks
|
|
2672
|
+
* Note: Subscriptions (subscribe(), countSubscribe(), paginateSubscribe()) default to SurrealDB live queries
|
|
2673
|
+
* if useSurrealDB(true) is set (default).
|
|
2674
|
+
*/
|
|
2675
|
+
useSurrealDB(enabled: boolean = true): ModelQueryBuilder<T> {
|
|
2676
|
+
this.useSurrealDBFlag = enabled;
|
|
2677
|
+
return this;
|
|
2678
|
+
}
|
|
2679
|
+
|
|
1078
2680
|
/**
|
|
1079
2681
|
* Executes the query once and returns the results.
|
|
1080
2682
|
*
|
|
@@ -1088,58 +2690,93 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
|
|
|
1088
2690
|
* ```
|
|
1089
2691
|
*/
|
|
1090
2692
|
async get(): Promise<T[]> {
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
2693
|
+
if (this.useSurrealDBFlag) {
|
|
2694
|
+
const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
|
|
2695
|
+
const result = await this.perspective.querySurrealDB(surrealQuery);
|
|
2696
|
+
const { results } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
|
|
2697
|
+
return results as T[];
|
|
2698
|
+
} else {
|
|
2699
|
+
const query = await this.ctor.queryToProlog(this.perspective, this.queryParams, this.modelClassName);
|
|
2700
|
+
const result = await this.perspective.infer(query);
|
|
2701
|
+
const { results } = await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, result);
|
|
2702
|
+
return results as T[];
|
|
2703
|
+
}
|
|
1095
2704
|
}
|
|
1096
2705
|
|
|
1097
2706
|
/**
|
|
1098
2707
|
* Subscribes to the query and receives updates when results change.
|
|
1099
|
-
*
|
|
2708
|
+
*
|
|
1100
2709
|
* This method:
|
|
1101
|
-
* 1. Creates and initializes a
|
|
2710
|
+
* 1. Creates and initializes a SurrealDB live query subscription (default)
|
|
1102
2711
|
* 2. Sets up the callback to process future updates
|
|
1103
2712
|
* 3. Returns the initial results immediately
|
|
1104
|
-
*
|
|
2713
|
+
*
|
|
1105
2714
|
* Remember to call dispose() when you're done with the subscription
|
|
1106
2715
|
* to clean up resources.
|
|
1107
|
-
*
|
|
2716
|
+
*
|
|
1108
2717
|
* @param callback - Function to call with updated results
|
|
1109
2718
|
* @returns Initial results array
|
|
1110
|
-
*
|
|
2719
|
+
*
|
|
1111
2720
|
* @example
|
|
1112
2721
|
* ```typescript
|
|
1113
2722
|
* const builder = Recipe.query(perspective)
|
|
1114
2723
|
* .where({ status: "cooking" });
|
|
1115
|
-
*
|
|
2724
|
+
*
|
|
1116
2725
|
* const initialRecipes = await builder.subscribe(recipes => {
|
|
1117
2726
|
* console.log("Updated recipes:", recipes);
|
|
1118
2727
|
* });
|
|
1119
|
-
*
|
|
2728
|
+
*
|
|
1120
2729
|
* // When done with subscription:
|
|
1121
2730
|
* builder.dispose();
|
|
1122
2731
|
* ```
|
|
2732
|
+
*
|
|
2733
|
+
* @remarks
|
|
2734
|
+
* By default, this uses SurrealDB live queries for real-time updates.
|
|
2735
|
+
* Prolog subscriptions remain available via `.useSurrealDB(false)`.
|
|
1123
2736
|
*/
|
|
1124
2737
|
async subscribe(callback: (results: T[]) => void): Promise<T[]> {
|
|
1125
2738
|
// Clean up any existing subscription
|
|
1126
2739
|
this.dispose();
|
|
1127
2740
|
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
2741
|
+
if (this.useSurrealDBFlag) {
|
|
2742
|
+
const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
|
|
2743
|
+
this.currentSubscription = await this.perspective.subscribeSurrealDB(surrealQuery);
|
|
2744
|
+
|
|
2745
|
+
const processResults = async (result: any) => {
|
|
2746
|
+
// The result from live query subscription update (handled in PerspectiveInstance listener)
|
|
2747
|
+
// is the new full set of results (because we re-query in Rust).
|
|
2748
|
+
// So we just need to map it to instances.
|
|
2749
|
+
const { results } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
|
|
2750
|
+
callback(results as T[]);
|
|
2751
|
+
};
|
|
2752
|
+
|
|
2753
|
+
this.currentSubscription.onResult(processResults);
|
|
2754
|
+
|
|
2755
|
+
// Process initial result
|
|
2756
|
+
const { results } = await this.ctor.instancesFromSurrealResult(
|
|
2757
|
+
this.perspective,
|
|
2758
|
+
this.queryParams,
|
|
2759
|
+
this.currentSubscription.result
|
|
2760
|
+
);
|
|
2761
|
+
return results as T[];
|
|
2762
|
+
} else {
|
|
2763
|
+
// Note: Subscriptions currently only work with Prolog
|
|
2764
|
+
const query = await this.ctor.queryToProlog(this.perspective, this.queryParams, this.modelClassName);
|
|
2765
|
+
this.currentSubscription = await this.perspective.subscribeInfer(query);
|
|
2766
|
+
|
|
2767
|
+
const processResults = async (result: AllInstancesResult) => {
|
|
2768
|
+
const { results } = await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, result);
|
|
2769
|
+
callback(results as T[]);
|
|
2770
|
+
};
|
|
2771
|
+
|
|
2772
|
+
this.currentSubscription.onResult(processResults);
|
|
2773
|
+
const { results } = await this.ctor.instancesFromPrologResult(
|
|
2774
|
+
this.perspective,
|
|
2775
|
+
this.queryParams,
|
|
2776
|
+
this.currentSubscription.result
|
|
2777
|
+
);
|
|
2778
|
+
return results as T[];
|
|
2779
|
+
}
|
|
1143
2780
|
}
|
|
1144
2781
|
|
|
1145
2782
|
/**
|
|
@@ -1155,52 +2792,84 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
|
|
|
1155
2792
|
* ```
|
|
1156
2793
|
*/
|
|
1157
2794
|
async count(): Promise<number> {
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
2795
|
+
if (this.useSurrealDBFlag) {
|
|
2796
|
+
const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
|
|
2797
|
+
const result = await this.perspective.querySurrealDB(surrealQuery);
|
|
2798
|
+
// Use instancesFromSurrealResult to apply JS-level filtering for advanced where conditions
|
|
2799
|
+
// (e.g., gt, gte, lt, lte, between, contains on properties and author/timestamp)
|
|
2800
|
+
// This ensures count() returns the same number as get().length
|
|
2801
|
+
const { totalCount } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
|
|
2802
|
+
return totalCount;
|
|
2803
|
+
} else {
|
|
2804
|
+
const query = await this.ctor.countQueryToProlog(this.perspective, this.queryParams, this.modelClassName);
|
|
2805
|
+
const result = await this.perspective.infer(query);
|
|
2806
|
+
return result?.[0]?.TotalCount || 0;
|
|
2807
|
+
}
|
|
1161
2808
|
}
|
|
1162
2809
|
|
|
1163
2810
|
/**
|
|
1164
2811
|
* Subscribes to count updates for matching entities.
|
|
1165
|
-
*
|
|
2812
|
+
*
|
|
1166
2813
|
* This method:
|
|
1167
|
-
* 1. Creates and initializes a
|
|
2814
|
+
* 1. Creates and initializes a SurrealDB live query subscription for the count (default)
|
|
1168
2815
|
* 2. Sets up the callback to process future count updates
|
|
1169
2816
|
* 3. Returns the initial count immediately
|
|
1170
|
-
*
|
|
2817
|
+
*
|
|
1171
2818
|
* Remember to call dispose() when you're done with the subscription
|
|
1172
2819
|
* to clean up resources.
|
|
1173
|
-
*
|
|
2820
|
+
*
|
|
1174
2821
|
* @param callback - Function to call with updated count
|
|
1175
2822
|
* @returns Initial count
|
|
1176
|
-
*
|
|
2823
|
+
*
|
|
1177
2824
|
* @example
|
|
1178
2825
|
* ```typescript
|
|
1179
2826
|
* const builder = Recipe.query(perspective)
|
|
1180
2827
|
* .where({ status: "active" });
|
|
1181
|
-
*
|
|
2828
|
+
*
|
|
1182
2829
|
* const initialCount = await builder.countSubscribe(count => {
|
|
1183
2830
|
* console.log("Active items:", count);
|
|
1184
2831
|
* });
|
|
1185
|
-
*
|
|
2832
|
+
*
|
|
1186
2833
|
* // When done with subscription:
|
|
1187
2834
|
* builder.dispose();
|
|
1188
2835
|
* ```
|
|
2836
|
+
*
|
|
2837
|
+
* @remarks
|
|
2838
|
+
* By default, this uses SurrealDB live queries for real-time updates.
|
|
2839
|
+
* Prolog subscriptions remain available via `.useSurrealDB(false)`.
|
|
1189
2840
|
*/
|
|
1190
2841
|
async countSubscribe(callback: (count: number) => void): Promise<number> {
|
|
1191
2842
|
// Clean up any existing subscription
|
|
1192
2843
|
this.dispose();
|
|
1193
2844
|
|
|
1194
|
-
|
|
1195
|
-
|
|
2845
|
+
if (this.useSurrealDBFlag) {
|
|
2846
|
+
const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
|
|
2847
|
+
this.currentSubscription = await this.perspective.subscribeSurrealDB(surrealQuery);
|
|
1196
2848
|
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
2849
|
+
const processResults = async (result: any) => {
|
|
2850
|
+
const { totalCount } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
|
|
2851
|
+
callback(totalCount);
|
|
2852
|
+
};
|
|
1201
2853
|
|
|
1202
|
-
|
|
1203
|
-
|
|
2854
|
+
this.currentSubscription.onResult(processResults);
|
|
2855
|
+
const { totalCount } = await this.ctor.instancesFromSurrealResult(
|
|
2856
|
+
this.perspective,
|
|
2857
|
+
this.queryParams,
|
|
2858
|
+
this.currentSubscription.result
|
|
2859
|
+
);
|
|
2860
|
+
return totalCount;
|
|
2861
|
+
} else {
|
|
2862
|
+
const query = await this.ctor.countQueryToProlog(this.perspective, this.queryParams, this.modelClassName);
|
|
2863
|
+
this.currentSubscription = await this.perspective.subscribeInfer(query);
|
|
2864
|
+
|
|
2865
|
+
const processResults = async (result: any) => {
|
|
2866
|
+
const newCount = result?.[0]?.TotalCount || 0;
|
|
2867
|
+
callback(newCount);
|
|
2868
|
+
};
|
|
2869
|
+
|
|
2870
|
+
this.currentSubscription.onResult(processResults);
|
|
2871
|
+
return this.currentSubscription.result?.[0]?.TotalCount || 0;
|
|
2872
|
+
}
|
|
1204
2873
|
}
|
|
1205
2874
|
|
|
1206
2875
|
/**
|
|
@@ -1220,40 +2889,51 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
|
|
|
1220
2889
|
*/
|
|
1221
2890
|
async paginate(pageSize: number, pageNumber: number): Promise<PaginationResult<T>> {
|
|
1222
2891
|
const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
2892
|
+
if (this.useSurrealDBFlag) {
|
|
2893
|
+
const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, paginationQuery);
|
|
2894
|
+
const result = await this.perspective.querySurrealDB(surrealQuery);
|
|
2895
|
+
const { results, totalCount } = (await this.ctor.instancesFromSurrealResult(this.perspective, paginationQuery, result)) as ResultsWithTotalCount<T>;
|
|
2896
|
+
return { results, totalCount, pageSize, pageNumber };
|
|
2897
|
+
} else {
|
|
2898
|
+
const prologQuery = await this.ctor.queryToProlog(this.perspective, paginationQuery, this.modelClassName);
|
|
2899
|
+
const result = await this.perspective.infer(prologQuery);
|
|
2900
|
+
const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, paginationQuery, result)) as ResultsWithTotalCount<T>;
|
|
2901
|
+
return { results, totalCount, pageSize, pageNumber };
|
|
2902
|
+
}
|
|
1227
2903
|
}
|
|
1228
2904
|
|
|
1229
2905
|
/**
|
|
1230
2906
|
* Subscribes to paginated results updates.
|
|
1231
|
-
*
|
|
2907
|
+
*
|
|
1232
2908
|
* This method:
|
|
1233
|
-
* 1. Creates and initializes a
|
|
2909
|
+
* 1. Creates and initializes a SurrealDB live query subscription for the paginated results (default)
|
|
1234
2910
|
* 2. Sets up the callback to process future page updates
|
|
1235
2911
|
* 3. Returns the initial page immediately
|
|
1236
|
-
*
|
|
2912
|
+
*
|
|
1237
2913
|
* Remember to call dispose() when you're done with the subscription
|
|
1238
2914
|
* to clean up resources.
|
|
1239
|
-
*
|
|
2915
|
+
*
|
|
1240
2916
|
* @param pageSize - Number of items per page
|
|
1241
2917
|
* @param pageNumber - Which page to retrieve (1-based)
|
|
1242
2918
|
* @param callback - Function to call with updated pagination results
|
|
1243
2919
|
* @returns Initial pagination results
|
|
1244
|
-
*
|
|
2920
|
+
*
|
|
1245
2921
|
* @example
|
|
1246
2922
|
* ```typescript
|
|
1247
2923
|
* const builder = Recipe.query(perspective)
|
|
1248
2924
|
* .where({ category: "Main" });
|
|
1249
|
-
*
|
|
2925
|
+
*
|
|
1250
2926
|
* const initialPage = await builder.paginateSubscribe(10, 1, page => {
|
|
1251
2927
|
* console.log("Updated page:", page.results);
|
|
1252
2928
|
* });
|
|
1253
|
-
*
|
|
2929
|
+
*
|
|
1254
2930
|
* // When done with subscription:
|
|
1255
2931
|
* builder.dispose();
|
|
1256
2932
|
* ```
|
|
2933
|
+
*
|
|
2934
|
+
* @remarks
|
|
2935
|
+
* By default, this uses SurrealDB live queries for real-time updates.
|
|
2936
|
+
* Prolog subscriptions remain available via `.useSurrealDB(false)`.
|
|
1257
2937
|
*/
|
|
1258
2938
|
async paginateSubscribe(
|
|
1259
2939
|
pageSize: number,
|
|
@@ -1264,16 +2944,31 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
|
|
|
1264
2944
|
this.dispose();
|
|
1265
2945
|
|
|
1266
2946
|
const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
|
|
1267
|
-
const prologQuery = await this.ctor.queryToProlog(this.perspective, paginationQuery, this.modelClassName);
|
|
1268
|
-
this.currentSubscription = await this.perspective.subscribeInfer(prologQuery);
|
|
1269
2947
|
|
|
1270
|
-
|
|
1271
|
-
const
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
2948
|
+
if (this.useSurrealDBFlag) {
|
|
2949
|
+
const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, paginationQuery);
|
|
2950
|
+
this.currentSubscription = await this.perspective.subscribeSurrealDB(surrealQuery);
|
|
2951
|
+
|
|
2952
|
+
const processResults = async (result: any) => {
|
|
2953
|
+
const { results, totalCount } = (await this.ctor.instancesFromSurrealResult(this.perspective, paginationQuery, result)) as ResultsWithTotalCount<T>;
|
|
2954
|
+
callback({ results, totalCount, pageSize, pageNumber });
|
|
2955
|
+
};
|
|
2956
|
+
|
|
2957
|
+
this.currentSubscription.onResult(processResults);
|
|
2958
|
+
const { results, totalCount } = (await this.ctor.instancesFromSurrealResult(this.perspective, paginationQuery, this.currentSubscription.result)) as ResultsWithTotalCount<T>;
|
|
2959
|
+
return { results, totalCount, pageSize, pageNumber };
|
|
2960
|
+
} else {
|
|
2961
|
+
const prologQuery = await this.ctor.queryToProlog(this.perspective, paginationQuery, this.modelClassName);
|
|
2962
|
+
this.currentSubscription = await this.perspective.subscribeInfer(prologQuery);
|
|
2963
|
+
|
|
2964
|
+
const processResults = async (r: AllInstancesResult) => {
|
|
2965
|
+
const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, r)) as ResultsWithTotalCount<T>;
|
|
2966
|
+
callback({ results, totalCount, pageSize, pageNumber });
|
|
2967
|
+
};
|
|
2968
|
+
|
|
2969
|
+
this.currentSubscription.onResult(processResults);
|
|
2970
|
+
const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, paginationQuery, this.currentSubscription.result)) as ResultsWithTotalCount<T>;
|
|
2971
|
+
return { results, totalCount, pageSize, pageNumber };
|
|
2972
|
+
}
|
|
1278
2973
|
}
|
|
1279
2974
|
}
|