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