@coasys/ad4m 0.10.1-release-candidate-5 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/index.cjs +1716 -87
- package/lib/index.js +1716 -87
- package/lib/src/model/Ad4mModel.d.ts +423 -9
- package/lib/src/model/Ad4mModel.js +1499 -61
- package/lib/src/model/Ad4mModel.test.d.ts +1 -0
- package/lib/src/model/Ad4mModel.test.js +1325 -0
- package/lib/src/perspectives/PerspectiveClient.d.ts +17 -0
- package/lib/src/perspectives/PerspectiveClient.js +61 -0
- package/lib/src/perspectives/PerspectiveProxy.d.ts +52 -1
- package/lib/src/perspectives/PerspectiveProxy.js +157 -28
- package/lib/src/perspectives/PerspectiveResolver.d.ts +1 -0
- package/lib/src/perspectives/PerspectiveResolver.js +11 -0
- package/lib/src/schema.gql +1 -0
- package/lib/src/typeDefs.js +1 -0
- package/package.json +1 -1
- package/src/model/Ad4mModel.test.ts +1476 -0
- package/src/model/Ad4mModel.ts +1758 -87
- package/src/perspectives/PerspectiveClient.ts +67 -0
- package/src/perspectives/PerspectiveProxy.ts +175 -35
- package/src/perspectives/PerspectiveResolver.ts +8 -0
package/lib/index.cjs
CHANGED
|
@@ -4614,7 +4614,7 @@ var __classPrivateFieldGet$a = (undefined && undefined.__classPrivateFieldGet) |
|
|
|
4614
4614
|
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
4615
4615
|
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
4616
4616
|
};
|
|
4617
|
-
var _QuerySubscriptionProxy_instances, _QuerySubscriptionProxy_uuid, _QuerySubscriptionProxy_subscriptionId, _QuerySubscriptionProxy_client, _QuerySubscriptionProxy_callbacks, _QuerySubscriptionProxy_keepaliveTimer, _QuerySubscriptionProxy_unsubscribe, _QuerySubscriptionProxy_latestResult, _QuerySubscriptionProxy_disposed, _QuerySubscriptionProxy_initialized, _QuerySubscriptionProxy_initTimeoutId, _QuerySubscriptionProxy_query, _QuerySubscriptionProxy_notifyCallbacks, _PerspectiveProxy_handle, _PerspectiveProxy_client, _PerspectiveProxy_perspectiveLinkAddedCallbacks, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks;
|
|
4617
|
+
var _QuerySubscriptionProxy_instances, _QuerySubscriptionProxy_uuid, _QuerySubscriptionProxy_subscriptionId, _QuerySubscriptionProxy_client, _QuerySubscriptionProxy_callbacks, _QuerySubscriptionProxy_keepaliveTimer, _QuerySubscriptionProxy_unsubscribe, _QuerySubscriptionProxy_latestResult, _QuerySubscriptionProxy_disposed, _QuerySubscriptionProxy_initialized, _QuerySubscriptionProxy_initResolve, _QuerySubscriptionProxy_initReject, _QuerySubscriptionProxy_initTimeoutId, _QuerySubscriptionProxy_query, _QuerySubscriptionProxy_notifyCallbacks, _PerspectiveProxy_handle, _PerspectiveProxy_client, _PerspectiveProxy_perspectiveLinkAddedCallbacks, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks;
|
|
4618
4618
|
/** Proxy object for a subscribed Prolog query that provides real-time updates
|
|
4619
4619
|
*
|
|
4620
4620
|
* This class handles:
|
|
@@ -4665,56 +4665,119 @@ class QuerySubscriptionProxy {
|
|
|
4665
4665
|
_QuerySubscriptionProxy_latestResult.set(this, void 0);
|
|
4666
4666
|
_QuerySubscriptionProxy_disposed.set(this, false);
|
|
4667
4667
|
_QuerySubscriptionProxy_initialized.set(this, void 0);
|
|
4668
|
+
_QuerySubscriptionProxy_initResolve.set(this, void 0);
|
|
4669
|
+
_QuerySubscriptionProxy_initReject.set(this, void 0);
|
|
4668
4670
|
_QuerySubscriptionProxy_initTimeoutId.set(this, void 0);
|
|
4669
4671
|
_QuerySubscriptionProxy_query.set(this, void 0);
|
|
4672
|
+
this.isSurrealDB = false;
|
|
4670
4673
|
__classPrivateFieldSet$a(this, _QuerySubscriptionProxy_uuid, uuid, "f");
|
|
4671
4674
|
__classPrivateFieldSet$a(this, _QuerySubscriptionProxy_query, query, "f");
|
|
4672
4675
|
__classPrivateFieldSet$a(this, _QuerySubscriptionProxy_client, client, "f");
|
|
4673
4676
|
__classPrivateFieldSet$a(this, _QuerySubscriptionProxy_callbacks, new Set(), "f");
|
|
4674
4677
|
__classPrivateFieldSet$a(this, _QuerySubscriptionProxy_latestResult, null, "f");
|
|
4678
|
+
// Create the promise once and store its resolve/reject
|
|
4679
|
+
__classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initialized, new Promise((resolve, reject) => {
|
|
4680
|
+
__classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initResolve, resolve, "f");
|
|
4681
|
+
__classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initReject, reject, "f");
|
|
4682
|
+
}), "f");
|
|
4675
4683
|
}
|
|
4676
4684
|
async subscribe() {
|
|
4677
|
-
//
|
|
4678
|
-
|
|
4679
|
-
|
|
4680
|
-
|
|
4681
|
-
|
|
4682
|
-
|
|
4685
|
+
// Clean up previous subscription attempt if retrying
|
|
4686
|
+
if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_unsubscribe, "f")) {
|
|
4687
|
+
__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_unsubscribe, "f").call(this);
|
|
4688
|
+
__classPrivateFieldSet$a(this, _QuerySubscriptionProxy_unsubscribe, undefined, "f");
|
|
4689
|
+
}
|
|
4690
|
+
// Clear any existing timeout
|
|
4691
|
+
if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, "f")) {
|
|
4692
|
+
clearTimeout(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, "f"));
|
|
4693
|
+
__classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initTimeoutId, undefined, "f");
|
|
4694
|
+
}
|
|
4695
|
+
// Clear any existing keepalive timer to prevent accumulation
|
|
4696
|
+
if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_keepaliveTimer, "f")) {
|
|
4697
|
+
clearTimeout(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_keepaliveTimer, "f"));
|
|
4698
|
+
__classPrivateFieldSet$a(this, _QuerySubscriptionProxy_keepaliveTimer, undefined, "f");
|
|
4699
|
+
}
|
|
4700
|
+
try {
|
|
4701
|
+
// Initialize the query subscription
|
|
4702
|
+
let initialResult;
|
|
4703
|
+
if (this.isSurrealDB) {
|
|
4704
|
+
initialResult = await __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").perspectiveSubscribeSurrealQuery(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_query, "f"));
|
|
4705
|
+
}
|
|
4706
|
+
else {
|
|
4707
|
+
initialResult = await __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").subscribeQuery(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_query, "f"));
|
|
4708
|
+
}
|
|
4709
|
+
__classPrivateFieldSet$a(this, _QuerySubscriptionProxy_subscriptionId, initialResult.subscriptionId, "f");
|
|
4710
|
+
// Process the initial result immediately for fast UX
|
|
4711
|
+
if (initialResult.result) {
|
|
4712
|
+
__classPrivateFieldSet$a(this, _QuerySubscriptionProxy_latestResult, initialResult.result, "f");
|
|
4713
|
+
__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_notifyCallbacks).call(this, initialResult.result);
|
|
4714
|
+
}
|
|
4715
|
+
else {
|
|
4716
|
+
console.warn('⚠️ No initial result returned from subscribeQuery!');
|
|
4717
|
+
}
|
|
4718
|
+
// Set up timeout for retry
|
|
4683
4719
|
__classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initTimeoutId, setTimeout(() => {
|
|
4684
|
-
|
|
4685
|
-
|
|
4686
|
-
|
|
4720
|
+
console.error('Subscription initialization timed out after 30 seconds. Resubscribing...');
|
|
4721
|
+
// Recursively retry subscription, catching any errors
|
|
4722
|
+
this.subscribe().catch(error => {
|
|
4723
|
+
console.error('Error during subscription retry after timeout:', error);
|
|
4724
|
+
});
|
|
4725
|
+
}, 30000), "f");
|
|
4687
4726
|
// Subscribe to query updates
|
|
4688
|
-
__classPrivateFieldSet$a(this, _QuerySubscriptionProxy_unsubscribe, __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").subscribeToQueryUpdates(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_subscriptionId, "f"), (
|
|
4727
|
+
__classPrivateFieldSet$a(this, _QuerySubscriptionProxy_unsubscribe, __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").subscribeToQueryUpdates(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_subscriptionId, "f"), (updateResult) => {
|
|
4728
|
+
// Clear timeout on first message
|
|
4689
4729
|
if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, "f")) {
|
|
4690
4730
|
clearTimeout(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, "f"));
|
|
4691
4731
|
__classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initTimeoutId, undefined, "f");
|
|
4692
4732
|
}
|
|
4693
|
-
|
|
4694
|
-
|
|
4695
|
-
|
|
4696
|
-
|
|
4697
|
-
|
|
4698
|
-
if (result.isInit && __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_latestResult, "f")) {
|
|
4699
|
-
return;
|
|
4733
|
+
// Resolve the initialization promise (only resolves once)
|
|
4734
|
+
if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initResolve, "f")) {
|
|
4735
|
+
__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initResolve, "f").call(this, true);
|
|
4736
|
+
__classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initResolve, undefined, "f"); // Prevent double-resolve
|
|
4737
|
+
__classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initReject, undefined, "f");
|
|
4700
4738
|
}
|
|
4701
|
-
|
|
4702
|
-
__classPrivateFieldGet$a(this,
|
|
4739
|
+
// Skip duplicate init messages
|
|
4740
|
+
if (updateResult.isInit && __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_latestResult, "f"))
|
|
4741
|
+
return;
|
|
4742
|
+
__classPrivateFieldSet$a(this, _QuerySubscriptionProxy_latestResult, updateResult, "f");
|
|
4743
|
+
__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_notifyCallbacks).call(this, updateResult);
|
|
4703
4744
|
}), "f");
|
|
4704
|
-
}
|
|
4745
|
+
}
|
|
4746
|
+
catch (error) {
|
|
4747
|
+
console.error('Error setting up subscription:', error);
|
|
4748
|
+
// Reject the promise if this is the first attempt
|
|
4749
|
+
if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initReject, "f")) {
|
|
4750
|
+
__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initReject, "f").call(this, error);
|
|
4751
|
+
__classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initResolve, undefined, "f");
|
|
4752
|
+
__classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initReject, undefined, "f");
|
|
4753
|
+
}
|
|
4754
|
+
throw error; // Re-throw so caller knows it failed
|
|
4755
|
+
}
|
|
4705
4756
|
// Start keepalive loop using platform-agnostic setTimeout
|
|
4706
4757
|
const keepaliveLoop = async () => {
|
|
4707
4758
|
if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f"))
|
|
4708
4759
|
return;
|
|
4709
4760
|
try {
|
|
4710
|
-
|
|
4761
|
+
if (this.isSurrealDB) {
|
|
4762
|
+
await __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").perspectiveKeepAliveSurrealQuery(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_subscriptionId, "f"));
|
|
4763
|
+
}
|
|
4764
|
+
else {
|
|
4765
|
+
await __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").keepAliveQuery(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_subscriptionId, "f"));
|
|
4766
|
+
}
|
|
4711
4767
|
}
|
|
4712
4768
|
catch (e) {
|
|
4713
4769
|
console.error('Error in keepalive:', e);
|
|
4714
4770
|
// try to reinitialize the subscription
|
|
4715
4771
|
console.log('Reinitializing subscription for query:', __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_query, "f"));
|
|
4716
|
-
|
|
4717
|
-
|
|
4772
|
+
try {
|
|
4773
|
+
await this.subscribe();
|
|
4774
|
+
console.log('Subscription reinitialized');
|
|
4775
|
+
}
|
|
4776
|
+
catch (resubscribeError) {
|
|
4777
|
+
console.error('Error during resubscription from keepalive:', resubscribeError);
|
|
4778
|
+
// Don't schedule another keepalive on resubscribe failure
|
|
4779
|
+
return;
|
|
4780
|
+
}
|
|
4718
4781
|
}
|
|
4719
4782
|
// Schedule next keepalive if not disposed
|
|
4720
4783
|
if (!__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f")) {
|
|
@@ -4739,7 +4802,9 @@ class QuerySubscriptionProxy {
|
|
|
4739
4802
|
* through the subscription channel. This ensures the subscription is fully
|
|
4740
4803
|
* set up before allowing access to results or updates.
|
|
4741
4804
|
*
|
|
4742
|
-
*
|
|
4805
|
+
* If no result is received within 30 seconds, the subscription will automatically
|
|
4806
|
+
* retry. The promise will remain pending until a subscription message successfully
|
|
4807
|
+
* arrives, or until a fatal error occurs during subscription setup.
|
|
4743
4808
|
*
|
|
4744
4809
|
* Note: You typically don't need to await this directly since the subscription
|
|
4745
4810
|
* creation methods (like subscribeInfer) already wait for initialization.
|
|
@@ -4805,12 +4870,18 @@ class QuerySubscriptionProxy {
|
|
|
4805
4870
|
}
|
|
4806
4871
|
// Tell the backend to dispose of the subscription
|
|
4807
4872
|
if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_subscriptionId, "f")) {
|
|
4808
|
-
|
|
4809
|
-
|
|
4873
|
+
if (this.isSurrealDB) {
|
|
4874
|
+
__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").perspectiveDisposeSurrealQuerySubscription(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_subscriptionId, "f"))
|
|
4875
|
+
.catch(e => console.error('Error disposing surreal query subscription:', e));
|
|
4876
|
+
}
|
|
4877
|
+
else {
|
|
4878
|
+
__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").disposeQuerySubscription(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_subscriptionId, "f"))
|
|
4879
|
+
.catch(e => console.error('Error disposing query subscription:', e));
|
|
4880
|
+
}
|
|
4810
4881
|
}
|
|
4811
4882
|
}
|
|
4812
4883
|
}
|
|
4813
|
-
_QuerySubscriptionProxy_uuid = new WeakMap(), _QuerySubscriptionProxy_subscriptionId = new WeakMap(), _QuerySubscriptionProxy_client = new WeakMap(), _QuerySubscriptionProxy_callbacks = new WeakMap(), _QuerySubscriptionProxy_keepaliveTimer = new WeakMap(), _QuerySubscriptionProxy_unsubscribe = new WeakMap(), _QuerySubscriptionProxy_latestResult = new WeakMap(), _QuerySubscriptionProxy_disposed = new WeakMap(), _QuerySubscriptionProxy_initialized = new WeakMap(), _QuerySubscriptionProxy_initTimeoutId = new WeakMap(), _QuerySubscriptionProxy_query = new WeakMap(), _QuerySubscriptionProxy_instances = new WeakSet(), _QuerySubscriptionProxy_notifyCallbacks = function _QuerySubscriptionProxy_notifyCallbacks(result) {
|
|
4884
|
+
_QuerySubscriptionProxy_uuid = new WeakMap(), _QuerySubscriptionProxy_subscriptionId = new WeakMap(), _QuerySubscriptionProxy_client = new WeakMap(), _QuerySubscriptionProxy_callbacks = new WeakMap(), _QuerySubscriptionProxy_keepaliveTimer = new WeakMap(), _QuerySubscriptionProxy_unsubscribe = new WeakMap(), _QuerySubscriptionProxy_latestResult = new WeakMap(), _QuerySubscriptionProxy_disposed = new WeakMap(), _QuerySubscriptionProxy_initialized = new WeakMap(), _QuerySubscriptionProxy_initResolve = new WeakMap(), _QuerySubscriptionProxy_initReject = new WeakMap(), _QuerySubscriptionProxy_initTimeoutId = new WeakMap(), _QuerySubscriptionProxy_query = new WeakMap(), _QuerySubscriptionProxy_instances = new WeakSet(), _QuerySubscriptionProxy_notifyCallbacks = function _QuerySubscriptionProxy_notifyCallbacks(result) {
|
|
4814
4885
|
for (const callback of __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_callbacks, "f")) {
|
|
4815
4886
|
try {
|
|
4816
4887
|
callback(result);
|
|
@@ -5000,6 +5071,36 @@ class PerspectiveProxy {
|
|
|
5000
5071
|
async infer(query) {
|
|
5001
5072
|
return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").queryProlog(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, query);
|
|
5002
5073
|
}
|
|
5074
|
+
/**
|
|
5075
|
+
* Executes a SurrealQL query against the perspective's link cache.
|
|
5076
|
+
* This allows powerful SQL-like queries on the link data stored in SurrealDB.
|
|
5077
|
+
*
|
|
5078
|
+
* **Security Note:** Only read-only queries (SELECT, RETURN, etc.) are permitted.
|
|
5079
|
+
* Mutating operations (DELETE, UPDATE, INSERT, CREATE, DROP, DEFINE, etc.) are
|
|
5080
|
+
* blocked for security reasons. Use the perspective's add/remove methods to modify links.
|
|
5081
|
+
*
|
|
5082
|
+
* @param query - SurrealQL query string (read-only operations only)
|
|
5083
|
+
* @returns Query results as parsed JSON
|
|
5084
|
+
*
|
|
5085
|
+
* @example
|
|
5086
|
+
* ```typescript
|
|
5087
|
+
* // Get all links
|
|
5088
|
+
* const links = await perspective.querySurrealDB('SELECT * FROM link');
|
|
5089
|
+
*
|
|
5090
|
+
* // Filter links by predicate
|
|
5091
|
+
* const follows = await perspective.querySurrealDB(
|
|
5092
|
+
* "SELECT * FROM link WHERE predicate = 'follows'"
|
|
5093
|
+
* );
|
|
5094
|
+
*
|
|
5095
|
+
* // Complex aggregation query
|
|
5096
|
+
* const stats = await perspective.querySurrealDB(
|
|
5097
|
+
* "SELECT predicate, count() as total FROM link GROUP BY predicate"
|
|
5098
|
+
* );
|
|
5099
|
+
* ```
|
|
5100
|
+
*/
|
|
5101
|
+
async querySurrealDB(query) {
|
|
5102
|
+
return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").querySurrealDB(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, query);
|
|
5103
|
+
}
|
|
5003
5104
|
/**
|
|
5004
5105
|
* Adds a new link to the perspective.
|
|
5005
5106
|
*
|
|
@@ -5708,6 +5809,34 @@ class PerspectiveProxy {
|
|
|
5708
5809
|
await subscriptionProxy.initialized;
|
|
5709
5810
|
return subscriptionProxy;
|
|
5710
5811
|
}
|
|
5812
|
+
/**
|
|
5813
|
+
* Creates a subscription for a SurrealQL query that updates in real-time.
|
|
5814
|
+
*
|
|
5815
|
+
* This method:
|
|
5816
|
+
* 1. Creates the subscription on the Rust side
|
|
5817
|
+
* 2. Sets up the subscription callback
|
|
5818
|
+
* 3. Waits for the initial result to come through the subscription channel
|
|
5819
|
+
* 4. Returns a fully initialized QuerySubscriptionProxy
|
|
5820
|
+
*
|
|
5821
|
+
* The returned subscription is guaranteed to be ready to receive updates,
|
|
5822
|
+
* as this method waits for the initialization process to complete.
|
|
5823
|
+
*
|
|
5824
|
+
* The subscription will be automatically cleaned up on both frontend and backend
|
|
5825
|
+
* when dispose() is called. Make sure to call dispose() when you're done to
|
|
5826
|
+
* prevent memory leaks and ensure proper cleanup of resources.
|
|
5827
|
+
*
|
|
5828
|
+
* @param query - SurrealQL query string
|
|
5829
|
+
* @returns Initialized QuerySubscriptionProxy instance
|
|
5830
|
+
*/
|
|
5831
|
+
async subscribeSurrealDB(query) {
|
|
5832
|
+
const subscriptionProxy = new QuerySubscriptionProxy(this.uuid, query, __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f"));
|
|
5833
|
+
subscriptionProxy.isSurrealDB = true;
|
|
5834
|
+
// Start the subscription on the Rust side first to get the real subscription ID
|
|
5835
|
+
await subscriptionProxy.subscribe();
|
|
5836
|
+
// Wait for the initial result
|
|
5837
|
+
await subscriptionProxy.initialized;
|
|
5838
|
+
return subscriptionProxy;
|
|
5839
|
+
}
|
|
5711
5840
|
}
|
|
5712
5841
|
_PerspectiveProxy_handle = new WeakMap(), _PerspectiveProxy_client = new WeakMap(), _PerspectiveProxy_perspectiveLinkAddedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveLinkRemovedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveLinkUpdatedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveSyncStateChangeCallbacks = new WeakMap();
|
|
5713
5842
|
|
|
@@ -5847,6 +5976,24 @@ class PerspectiveClient {
|
|
|
5847
5976
|
}));
|
|
5848
5977
|
return JSON.parse(perspectiveQueryProlog);
|
|
5849
5978
|
}
|
|
5979
|
+
/**
|
|
5980
|
+
* Executes a read-only SurrealQL query against a perspective's link cache.
|
|
5981
|
+
*
|
|
5982
|
+
* Security: Only SELECT, RETURN, and other read-only queries are permitted.
|
|
5983
|
+
* Mutating operations (DELETE, UPDATE, INSERT, etc.) are blocked.
|
|
5984
|
+
*
|
|
5985
|
+
* Note: GraphQL field name is "perspectiveQuerySurrealDb" (lowercase "b" in "Db")
|
|
5986
|
+
* as generated from Rust method "perspective_query_surreal_db"
|
|
5987
|
+
*/
|
|
5988
|
+
async querySurrealDB(uuid, query) {
|
|
5989
|
+
const { perspectiveQuerySurrealDb } = unwrapApolloResult(await __classPrivateFieldGet$9(this, _PerspectiveClient_apolloClient, "f").query({
|
|
5990
|
+
query: gql `query perspectiveQuerySurrealDb($uuid: String!, $query: String!) {
|
|
5991
|
+
perspectiveQuerySurrealDb(uuid: $uuid, query: $query)
|
|
5992
|
+
}`,
|
|
5993
|
+
variables: { uuid, query }
|
|
5994
|
+
}));
|
|
5995
|
+
return JSON.parse(perspectiveQuerySurrealDb);
|
|
5996
|
+
}
|
|
5850
5997
|
async subscribeQuery(uuid, query) {
|
|
5851
5998
|
const { perspectiveSubscribeQuery } = unwrapApolloResult(await __classPrivateFieldGet$9(this, _PerspectiveClient_apolloClient, "f").mutate({
|
|
5852
5999
|
mutation: gql `mutation perspectiveSubscribeQuery($uuid: String!, $query: String!) {
|
|
@@ -5872,6 +6019,49 @@ class PerspectiveClient {
|
|
|
5872
6019
|
}
|
|
5873
6020
|
return { subscriptionId, result: finalResult, isInit };
|
|
5874
6021
|
}
|
|
6022
|
+
async perspectiveSubscribeSurrealQuery(uuid, query) {
|
|
6023
|
+
const { perspectiveSubscribeSurrealQuery } = unwrapApolloResult(await __classPrivateFieldGet$9(this, _PerspectiveClient_apolloClient, "f").mutate({
|
|
6024
|
+
mutation: gql `mutation perspectiveSubscribeSurrealQuery($uuid: String!, $query: String!) {
|
|
6025
|
+
perspectiveSubscribeSurrealQuery(uuid: $uuid, query: $query) {
|
|
6026
|
+
subscriptionId
|
|
6027
|
+
result
|
|
6028
|
+
}
|
|
6029
|
+
}`,
|
|
6030
|
+
variables: { uuid, query }
|
|
6031
|
+
}));
|
|
6032
|
+
const { subscriptionId, result } = perspectiveSubscribeSurrealQuery;
|
|
6033
|
+
let finalResult = result;
|
|
6034
|
+
let isInit = false;
|
|
6035
|
+
if (finalResult.startsWith("#init#")) {
|
|
6036
|
+
finalResult = finalResult.substring(6);
|
|
6037
|
+
isInit = true;
|
|
6038
|
+
}
|
|
6039
|
+
try {
|
|
6040
|
+
finalResult = JSON.parse(finalResult);
|
|
6041
|
+
}
|
|
6042
|
+
catch (e) {
|
|
6043
|
+
console.error('Error parsing perspectiveSubscribeSurrealQuery result:', e);
|
|
6044
|
+
}
|
|
6045
|
+
return { subscriptionId, result: finalResult, isInit };
|
|
6046
|
+
}
|
|
6047
|
+
async perspectiveKeepAliveSurrealQuery(uuid, subscriptionId) {
|
|
6048
|
+
const { perspectiveKeepAliveSurrealQuery } = unwrapApolloResult(await __classPrivateFieldGet$9(this, _PerspectiveClient_apolloClient, "f").mutate({
|
|
6049
|
+
mutation: gql `mutation perspectiveKeepAliveSurrealQuery($uuid: String!, $subscriptionId: String!) {
|
|
6050
|
+
perspectiveKeepAliveSurrealQuery(uuid: $uuid, subscriptionId: $subscriptionId)
|
|
6051
|
+
}`,
|
|
6052
|
+
variables: { uuid, subscriptionId }
|
|
6053
|
+
}));
|
|
6054
|
+
return perspectiveKeepAliveSurrealQuery;
|
|
6055
|
+
}
|
|
6056
|
+
async perspectiveDisposeSurrealQuerySubscription(uuid, subscriptionId) {
|
|
6057
|
+
const { perspectiveDisposeSurrealQuerySubscription } = unwrapApolloResult(await __classPrivateFieldGet$9(this, _PerspectiveClient_apolloClient, "f").mutate({
|
|
6058
|
+
mutation: gql `mutation perspectiveDisposeSurrealQuerySubscription($uuid: String!, $subscriptionId: String!) {
|
|
6059
|
+
perspectiveDisposeSurrealQuerySubscription(uuid: $uuid, subscriptionId: $subscriptionId)
|
|
6060
|
+
}`,
|
|
6061
|
+
variables: { uuid, subscriptionId }
|
|
6062
|
+
}));
|
|
6063
|
+
return perspectiveDisposeSurrealQuerySubscription;
|
|
6064
|
+
}
|
|
5875
6065
|
subscribeToQueryUpdates(subscriptionId, onData) {
|
|
5876
6066
|
const subscription = __classPrivateFieldGet$9(this, _PerspectiveClient_apolloClient, "f").subscribe({
|
|
5877
6067
|
query: gql `
|
|
@@ -16797,6 +16987,7 @@ type Query {
|
|
|
16797
16987
|
perspective(uuid: String!): PerspectiveHandle
|
|
16798
16988
|
perspectiveQueryLinks(query: LinkQuery!, uuid: String!): [LinkExpression!]
|
|
16799
16989
|
perspectiveQueryProlog(query: String!, uuid: String!): String!
|
|
16990
|
+
perspectiveQuerySurrealDB(query: String!, uuid: String!): String!
|
|
16800
16991
|
perspectiveSnapshot(uuid: String!): Perspective
|
|
16801
16992
|
perspectives: [PerspectiveHandle!]!
|
|
16802
16993
|
runtimeFriendStatus(did: String!): PerspectiveExpression
|
|
@@ -17695,6 +17886,42 @@ function buildLimitQuery(limit) {
|
|
|
17695
17886
|
return "AllInstances = InstancesWithOffset";
|
|
17696
17887
|
return `takeN(InstancesWithOffset, ${limit}, AllInstances)`;
|
|
17697
17888
|
}
|
|
17889
|
+
function normalizeNamespaceString(namespace) {
|
|
17890
|
+
if (!namespace)
|
|
17891
|
+
return '';
|
|
17892
|
+
if (namespace.includes('://')) {
|
|
17893
|
+
const [scheme, rest] = namespace.split('://');
|
|
17894
|
+
const path = (rest || '').replace(/\/+$/, '');
|
|
17895
|
+
return `${scheme}://${path}`;
|
|
17896
|
+
}
|
|
17897
|
+
else {
|
|
17898
|
+
return namespace.replace(/\/+$/, '');
|
|
17899
|
+
}
|
|
17900
|
+
}
|
|
17901
|
+
function normalizeSchemaType(type) {
|
|
17902
|
+
if (!type)
|
|
17903
|
+
return undefined;
|
|
17904
|
+
if (typeof type === "string")
|
|
17905
|
+
return type;
|
|
17906
|
+
if (Array.isArray(type) && type.length > 0) {
|
|
17907
|
+
const nonNull = type.find((t) => t !== "null");
|
|
17908
|
+
return nonNull || type[0];
|
|
17909
|
+
}
|
|
17910
|
+
return undefined;
|
|
17911
|
+
}
|
|
17912
|
+
function isSchemaType(schema, expectedType) {
|
|
17913
|
+
return normalizeSchemaType(schema.type) === expectedType;
|
|
17914
|
+
}
|
|
17915
|
+
function isArrayType(schema) {
|
|
17916
|
+
return isSchemaType(schema, "array");
|
|
17917
|
+
}
|
|
17918
|
+
function isObjectType(schema) {
|
|
17919
|
+
return isSchemaType(schema, "object");
|
|
17920
|
+
}
|
|
17921
|
+
function isNumericType(schema) {
|
|
17922
|
+
const normalized = normalizeSchemaType(schema.type);
|
|
17923
|
+
return normalized === "number" || normalized === "integer";
|
|
17924
|
+
}
|
|
17698
17925
|
/**
|
|
17699
17926
|
* Base class for defining data models in AD4M.
|
|
17700
17927
|
*
|
|
@@ -17815,6 +18042,126 @@ class Ad4mModel {
|
|
|
17815
18042
|
}
|
|
17816
18043
|
return classCache[perspectiveID];
|
|
17817
18044
|
}
|
|
18045
|
+
/**
|
|
18046
|
+
* Extracts metadata from decorators for query building.
|
|
18047
|
+
*
|
|
18048
|
+
* @description
|
|
18049
|
+
* This method reads the metadata stored by decorators (@Property, @Collection, etc.)
|
|
18050
|
+
* and returns it in a structured format that's easier to work with for query builders
|
|
18051
|
+
* and other systems that need to introspect model structure.
|
|
18052
|
+
*
|
|
18053
|
+
* The metadata includes:
|
|
18054
|
+
* - Class name from @ModelOptions
|
|
18055
|
+
* - Property metadata (predicates, types, constraints, etc.)
|
|
18056
|
+
* - Collection metadata (predicates, filters, etc.)
|
|
18057
|
+
*
|
|
18058
|
+
* For models created via `fromJSONSchema()`, this method will derive metadata from
|
|
18059
|
+
* the stored `__properties` and `__collections` structures that were populated during
|
|
18060
|
+
* the dynamic class creation. If these structures are empty but a JSON schema was
|
|
18061
|
+
* attached to the class, it can fall back to deriving metadata from that schema.
|
|
18062
|
+
*
|
|
18063
|
+
* @returns Structured metadata object containing className, properties, and collections
|
|
18064
|
+
* @throws Error if the class doesn't have @ModelOptions decorator
|
|
18065
|
+
*
|
|
18066
|
+
* @example
|
|
18067
|
+
* ```typescript
|
|
18068
|
+
* @ModelOptions({ name: "Recipe" })
|
|
18069
|
+
* class Recipe extends Ad4mModel {
|
|
18070
|
+
* @Property({ through: "recipe://name", resolveLanguage: "literal" })
|
|
18071
|
+
* name: string = "";
|
|
18072
|
+
*
|
|
18073
|
+
* @Collection({ through: "recipe://ingredient" })
|
|
18074
|
+
* ingredients: string[] = [];
|
|
18075
|
+
* }
|
|
18076
|
+
*
|
|
18077
|
+
* const metadata = Recipe.getModelMetadata();
|
|
18078
|
+
* console.log(metadata.className); // "Recipe"
|
|
18079
|
+
* console.log(metadata.properties.name.predicate); // "recipe://name"
|
|
18080
|
+
* console.log(metadata.collections.ingredients.predicate); // "recipe://ingredient"
|
|
18081
|
+
* ```
|
|
18082
|
+
*/
|
|
18083
|
+
static getModelMetadata() {
|
|
18084
|
+
// Access the prototype with any type to access decorator-added properties
|
|
18085
|
+
const prototype = this.prototype;
|
|
18086
|
+
// Validate that the class has @ModelOptions decorator
|
|
18087
|
+
// The decorator sets prototype.className, so we check for its existence
|
|
18088
|
+
if (!prototype.className || prototype.className === 'Ad4mModel') {
|
|
18089
|
+
throw new Error("Model class must be decorated with @ModelOptions");
|
|
18090
|
+
}
|
|
18091
|
+
// Extract className
|
|
18092
|
+
const className = prototype.className;
|
|
18093
|
+
// Extract properties from prototype.__properties
|
|
18094
|
+
const propertiesMetadata = {};
|
|
18095
|
+
const prototypeProperties = prototype.__properties || {};
|
|
18096
|
+
for (const [propertyName, opts] of Object.entries(prototypeProperties)) {
|
|
18097
|
+
const options = opts;
|
|
18098
|
+
propertiesMetadata[propertyName] = {
|
|
18099
|
+
name: propertyName,
|
|
18100
|
+
predicate: options.through || "",
|
|
18101
|
+
required: options.required || false,
|
|
18102
|
+
writable: options.writable || false,
|
|
18103
|
+
...(options.initial !== undefined && { initial: options.initial }),
|
|
18104
|
+
...(options.resolveLanguage !== undefined && { resolveLanguage: options.resolveLanguage }),
|
|
18105
|
+
...(options.getter !== undefined && { getter: options.getter }),
|
|
18106
|
+
...(options.setter !== undefined && { setter: options.setter }),
|
|
18107
|
+
...(options.local !== undefined && { local: options.local }),
|
|
18108
|
+
...(options.transform !== undefined && { transform: options.transform }),
|
|
18109
|
+
...(options.flag !== undefined && { flag: options.flag })
|
|
18110
|
+
};
|
|
18111
|
+
}
|
|
18112
|
+
// Extract collections from prototype.__collections
|
|
18113
|
+
const collectionsMetadata = {};
|
|
18114
|
+
const prototypeCollections = prototype.__collections || {};
|
|
18115
|
+
for (const [collectionName, opts] of Object.entries(prototypeCollections)) {
|
|
18116
|
+
const options = opts;
|
|
18117
|
+
collectionsMetadata[collectionName] = {
|
|
18118
|
+
name: collectionName,
|
|
18119
|
+
predicate: options.through || "",
|
|
18120
|
+
...(options.where !== undefined && { where: options.where }),
|
|
18121
|
+
...(options.local !== undefined && { local: options.local })
|
|
18122
|
+
};
|
|
18123
|
+
}
|
|
18124
|
+
// Fallback: If both structures are empty but a JSON schema is attached, derive from it
|
|
18125
|
+
// This handles edge cases where fromJSONSchema() was called but metadata wasn't properly populated
|
|
18126
|
+
const hasProperties = Object.keys(propertiesMetadata).length > 0;
|
|
18127
|
+
const hasCollections = Object.keys(collectionsMetadata).length > 0;
|
|
18128
|
+
const hasMetadata = hasProperties || hasCollections;
|
|
18129
|
+
if (!hasMetadata && prototype.__jsonSchema) {
|
|
18130
|
+
// Derive metadata from the attached JSON schema
|
|
18131
|
+
const schema = prototype.__jsonSchema;
|
|
18132
|
+
const options = prototype.__jsonSchemaOptions || {};
|
|
18133
|
+
if (schema.properties) {
|
|
18134
|
+
for (const [propertyName, propertySchema] of Object.entries(schema.properties)) {
|
|
18135
|
+
const isArray = isArrayType(propertySchema);
|
|
18136
|
+
const predicate = this.determinePredicate(schema, propertyName, propertySchema, this.determineNamespace(schema, options), options);
|
|
18137
|
+
if (isArray) {
|
|
18138
|
+
collectionsMetadata[propertyName] = {
|
|
18139
|
+
name: propertyName,
|
|
18140
|
+
predicate: predicate,
|
|
18141
|
+
...(propertySchema["x-ad4m"]?.local !== undefined && { local: propertySchema["x-ad4m"].local })
|
|
18142
|
+
};
|
|
18143
|
+
}
|
|
18144
|
+
else {
|
|
18145
|
+
const isRequired = schema.required?.includes(propertyName) || false;
|
|
18146
|
+
propertiesMetadata[propertyName] = {
|
|
18147
|
+
name: propertyName,
|
|
18148
|
+
predicate: predicate,
|
|
18149
|
+
required: isRequired,
|
|
18150
|
+
writable: propertySchema["x-ad4m"]?.writable !== false,
|
|
18151
|
+
...(propertySchema["x-ad4m"]?.resolveLanguage && { resolveLanguage: propertySchema["x-ad4m"].resolveLanguage }),
|
|
18152
|
+
...(propertySchema["x-ad4m"]?.initial && { initial: propertySchema["x-ad4m"].initial }),
|
|
18153
|
+
...(propertySchema["x-ad4m"]?.local !== undefined && { local: propertySchema["x-ad4m"].local })
|
|
18154
|
+
};
|
|
18155
|
+
}
|
|
18156
|
+
}
|
|
18157
|
+
}
|
|
18158
|
+
}
|
|
18159
|
+
return {
|
|
18160
|
+
className,
|
|
18161
|
+
properties: propertiesMetadata,
|
|
18162
|
+
collections: collectionsMetadata
|
|
18163
|
+
};
|
|
18164
|
+
}
|
|
17818
18165
|
/**
|
|
17819
18166
|
* Constructs a new model instance.
|
|
17820
18167
|
*
|
|
@@ -17942,6 +18289,477 @@ class Ad4mModel {
|
|
|
17942
18289
|
`;
|
|
17943
18290
|
return fullQuery;
|
|
17944
18291
|
}
|
|
18292
|
+
/**
|
|
18293
|
+
* Generates a SurrealQL query from a Query object.
|
|
18294
|
+
*
|
|
18295
|
+
* @description
|
|
18296
|
+
* This method translates high-level query parameters into a SurrealQL query string
|
|
18297
|
+
* that can be executed against the SurrealDB backend. Unlike Prolog queries which
|
|
18298
|
+
* operate on SDNA-aware predicates, SurrealQL queries operate directly on raw links
|
|
18299
|
+
* stored in SurrealDB.
|
|
18300
|
+
*
|
|
18301
|
+
* The generated query uses a CTE (Common Table Expression) pattern:
|
|
18302
|
+
* 1. First, identify candidate base expressions by filtering links based on where conditions
|
|
18303
|
+
* 2. Then, for each candidate base, resolve properties and collections via subqueries
|
|
18304
|
+
* 3. Finally, apply ordering, pagination (LIMIT/START) at the SQL level
|
|
18305
|
+
*
|
|
18306
|
+
* Key architectural notes:
|
|
18307
|
+
* - SurrealDB stores only raw links (source, predicate, target, author, timestamp)
|
|
18308
|
+
* - No SDNA knowledge at the database level
|
|
18309
|
+
* - Properties are resolved via subqueries that look for links with specific predicates
|
|
18310
|
+
* - Collections are similar but return multiple values instead of one
|
|
18311
|
+
* - Special fields (base, author, timestamp) are accessed directly, not via subqueries
|
|
18312
|
+
*
|
|
18313
|
+
* @param perspective - The perspective to query (used for metadata extraction)
|
|
18314
|
+
* @param query - Query parameters (where, order, limit, offset, properties, collections)
|
|
18315
|
+
* @returns Complete SurrealQL query string ready for execution
|
|
18316
|
+
*
|
|
18317
|
+
* @example
|
|
18318
|
+
* ```typescript
|
|
18319
|
+
* const query = Recipe.queryToSurrealQL(perspective, {
|
|
18320
|
+
* where: { name: "Pasta", rating: { gt: 4 } },
|
|
18321
|
+
* order: { timestamp: "DESC" },
|
|
18322
|
+
* limit: 10
|
|
18323
|
+
* });
|
|
18324
|
+
* // Returns: SELECT source AS base, array::first(target[WHERE predicate = ...]) AS name, ...
|
|
18325
|
+
* // FROM link WHERE ... GROUP BY source ORDER BY timestamp DESC LIMIT 10
|
|
18326
|
+
* ```
|
|
18327
|
+
*/
|
|
18328
|
+
static async queryToSurrealQL(perspective, query) {
|
|
18329
|
+
const metadata = this.getModelMetadata();
|
|
18330
|
+
const { source, where, order, offset, limit } = query;
|
|
18331
|
+
// Build list of graph traversal filters for required predicates
|
|
18332
|
+
const graphTraversalFilters = [];
|
|
18333
|
+
// Add source filter if specified (filter to nodes that are children of this source)
|
|
18334
|
+
// Source filter means: find targets of 'ad4m://has_child' links from the specified source
|
|
18335
|
+
if (source) {
|
|
18336
|
+
// Use graph traversal: node must be target of has_child link from source
|
|
18337
|
+
graphTraversalFilters.push(`count(<-link[WHERE perspective = $perspective AND in.uri = ${this.formatSurrealValue(source)} AND predicate = 'ad4m://has_child']) > 0`);
|
|
18338
|
+
}
|
|
18339
|
+
// Add filters for required properties
|
|
18340
|
+
for (const [propName, propMeta] of Object.entries(metadata.properties)) {
|
|
18341
|
+
if (propMeta.required) {
|
|
18342
|
+
// For flag properties, also filter by the target value
|
|
18343
|
+
if (propMeta.flag && propMeta.initial) {
|
|
18344
|
+
graphTraversalFilters.push(`count(->link[WHERE perspective = $perspective AND predicate = '${propMeta.predicate}' AND out.uri = '${propMeta.initial}']) > 0`);
|
|
18345
|
+
}
|
|
18346
|
+
else {
|
|
18347
|
+
graphTraversalFilters.push(`count(->link[WHERE perspective = $perspective AND predicate = '${propMeta.predicate}']) > 0`);
|
|
18348
|
+
}
|
|
18349
|
+
}
|
|
18350
|
+
}
|
|
18351
|
+
// If no required properties, we need at least one property to define the model
|
|
18352
|
+
// Use any property with an initial value as the defining characteristic
|
|
18353
|
+
if (graphTraversalFilters.length === 0) {
|
|
18354
|
+
for (const [propName, propMeta] of Object.entries(metadata.properties)) {
|
|
18355
|
+
if (propMeta.initial) {
|
|
18356
|
+
// For flag properties, also filter by the target value
|
|
18357
|
+
if (propMeta.flag) {
|
|
18358
|
+
graphTraversalFilters.push(`count(->link[WHERE perspective = $perspective AND predicate = '${propMeta.predicate}' AND out.uri = '${propMeta.initial}']) > 0`);
|
|
18359
|
+
}
|
|
18360
|
+
else {
|
|
18361
|
+
graphTraversalFilters.push(`count(->link[WHERE perspective = $perspective AND predicate = '${propMeta.predicate}']) > 0`);
|
|
18362
|
+
}
|
|
18363
|
+
break; // Just need one defining property
|
|
18364
|
+
}
|
|
18365
|
+
}
|
|
18366
|
+
}
|
|
18367
|
+
// Build user WHERE clause filters using graph traversal
|
|
18368
|
+
const userWhereClause = this.buildGraphTraversalWhereClause(metadata, where);
|
|
18369
|
+
// Build complete WHERE clause using graph traversal filters
|
|
18370
|
+
const whereConditions = [];
|
|
18371
|
+
// Add all graph traversal filters for required properties
|
|
18372
|
+
whereConditions.push(...graphTraversalFilters);
|
|
18373
|
+
// Add user where conditions if any
|
|
18374
|
+
if (userWhereClause) {
|
|
18375
|
+
whereConditions.push(userWhereClause);
|
|
18376
|
+
}
|
|
18377
|
+
// Always ensure node has at least one link in this perspective
|
|
18378
|
+
whereConditions.push(`count(->link[WHERE perspective = $perspective]) > 0`);
|
|
18379
|
+
// Build the query FROM node using direct graph traversal in WHERE
|
|
18380
|
+
// This avoids slow subqueries and uses graph indexes for fast traversal
|
|
18381
|
+
const fullQuery = `
|
|
18382
|
+
SELECT
|
|
18383
|
+
id AS source,
|
|
18384
|
+
uri AS source_uri,
|
|
18385
|
+
->link[WHERE perspective = $perspective] AS links
|
|
18386
|
+
FROM node
|
|
18387
|
+
WHERE ${whereConditions.join(' AND ')}
|
|
18388
|
+
`.trim();
|
|
18389
|
+
return fullQuery;
|
|
18390
|
+
}
|
|
18391
|
+
/**
|
|
18392
|
+
* Builds the WHERE clause for SurrealQL queries using graph traversal syntax.
|
|
18393
|
+
*
|
|
18394
|
+
* @description
|
|
18395
|
+
* Translates where conditions into graph traversal filters: `->link[WHERE ...]`
|
|
18396
|
+
* This is more efficient than nested SELECTs because SurrealDB can optimize graph traversals.
|
|
18397
|
+
*
|
|
18398
|
+
* Handles several condition types:
|
|
18399
|
+
* - Simple equality: `{ name: "Pasta" }` → `->link[WHERE predicate = 'X' AND out.uri = 'Pasta']`
|
|
18400
|
+
* - Arrays (IN clause): `{ name: ["Pasta", "Pizza"] }` → `->link[WHERE predicate = 'X' AND out.uri IN [...]]`
|
|
18401
|
+
* - NOT operators: Use `NOT` prefix
|
|
18402
|
+
* - Comparison operators (gt, gte, lt, lte, etc.): Handled in post-query JavaScript filtering
|
|
18403
|
+
* - Special fields: base uses `uri` directly, author/timestamp handled post-query
|
|
18404
|
+
*
|
|
18405
|
+
* @param metadata - Model metadata containing property predicates
|
|
18406
|
+
* @param where - Where conditions from the query
|
|
18407
|
+
* @returns Graph traversal WHERE clause filters, or empty string if no conditions
|
|
18408
|
+
*
|
|
18409
|
+
* @private
|
|
18410
|
+
*/
|
|
18411
|
+
static buildGraphTraversalWhereClause(metadata, where) {
|
|
18412
|
+
if (!where)
|
|
18413
|
+
return '';
|
|
18414
|
+
const conditions = [];
|
|
18415
|
+
for (const [propertyName, condition] of Object.entries(where)) {
|
|
18416
|
+
// Check if this is a special field (base, author, timestamp)
|
|
18417
|
+
// Note: author and timestamp filtering is done in JavaScript after query
|
|
18418
|
+
const isSpecial = ['base', 'author', 'timestamp'].includes(propertyName);
|
|
18419
|
+
if (isSpecial) {
|
|
18420
|
+
// Skip author and timestamp - they'll be filtered in JavaScript
|
|
18421
|
+
// Only handle 'base' (which maps to 'uri') here
|
|
18422
|
+
if (propertyName === 'author' || propertyName === 'timestamp') {
|
|
18423
|
+
continue; // Skip - will be filtered post-query
|
|
18424
|
+
}
|
|
18425
|
+
const columnName = 'uri'; // base maps to uri in node table
|
|
18426
|
+
// Handle base/uri field directly
|
|
18427
|
+
if (Array.isArray(condition)) {
|
|
18428
|
+
// Array values (IN clause)
|
|
18429
|
+
const formattedValues = condition.map(v => this.formatSurrealValue(v)).join(', ');
|
|
18430
|
+
conditions.push(`${columnName} IN [${formattedValues}]`);
|
|
18431
|
+
}
|
|
18432
|
+
else if (typeof condition === 'object' && condition !== null) {
|
|
18433
|
+
// Operator object
|
|
18434
|
+
const ops = condition;
|
|
18435
|
+
if (ops.not !== undefined) {
|
|
18436
|
+
if (Array.isArray(ops.not)) {
|
|
18437
|
+
const formattedValues = ops.not.map(v => this.formatSurrealValue(v)).join(', ');
|
|
18438
|
+
conditions.push(`${columnName} NOT IN [${formattedValues}]`);
|
|
18439
|
+
}
|
|
18440
|
+
else {
|
|
18441
|
+
conditions.push(`${columnName} != ${this.formatSurrealValue(ops.not)}`);
|
|
18442
|
+
}
|
|
18443
|
+
}
|
|
18444
|
+
if (ops.between !== undefined && Array.isArray(ops.between) && ops.between.length === 2) {
|
|
18445
|
+
conditions.push(`${columnName} >= ${this.formatSurrealValue(ops.between[0])} AND ${columnName} <= ${this.formatSurrealValue(ops.between[1])}`);
|
|
18446
|
+
}
|
|
18447
|
+
if (ops.gt !== undefined) {
|
|
18448
|
+
conditions.push(`${columnName} > ${this.formatSurrealValue(ops.gt)}`);
|
|
18449
|
+
}
|
|
18450
|
+
if (ops.gte !== undefined) {
|
|
18451
|
+
conditions.push(`${columnName} >= ${this.formatSurrealValue(ops.gte)}`);
|
|
18452
|
+
}
|
|
18453
|
+
if (ops.lt !== undefined) {
|
|
18454
|
+
conditions.push(`${columnName} < ${this.formatSurrealValue(ops.lt)}`);
|
|
18455
|
+
}
|
|
18456
|
+
if (ops.lte !== undefined) {
|
|
18457
|
+
conditions.push(`${columnName} <= ${this.formatSurrealValue(ops.lte)}`);
|
|
18458
|
+
}
|
|
18459
|
+
if (ops.contains !== undefined) {
|
|
18460
|
+
conditions.push(`${columnName} CONTAINS ${this.formatSurrealValue(ops.contains)}`);
|
|
18461
|
+
}
|
|
18462
|
+
}
|
|
18463
|
+
else {
|
|
18464
|
+
// Simple equality
|
|
18465
|
+
conditions.push(`${columnName} = ${this.formatSurrealValue(condition)}`);
|
|
18466
|
+
}
|
|
18467
|
+
}
|
|
18468
|
+
else {
|
|
18469
|
+
// Handle regular properties via graph traversal
|
|
18470
|
+
const propMeta = metadata.properties[propertyName];
|
|
18471
|
+
if (!propMeta)
|
|
18472
|
+
continue; // Skip if property not found in metadata
|
|
18473
|
+
const predicate = propMeta.predicate;
|
|
18474
|
+
// Use fn::parse_literal() for properties with resolveLanguage
|
|
18475
|
+
const targetField = propMeta.resolveLanguage === 'literal' ? 'fn::parse_literal(out.uri)' : 'out.uri';
|
|
18476
|
+
if (Array.isArray(condition)) {
|
|
18477
|
+
// Array values (IN clause)
|
|
18478
|
+
const formattedValues = condition.map(v => this.formatSurrealValue(v)).join(', ');
|
|
18479
|
+
conditions.push(`count(->link[WHERE perspective = $perspective AND predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) > 0`);
|
|
18480
|
+
}
|
|
18481
|
+
else if (typeof condition === 'object' && condition !== null) {
|
|
18482
|
+
// Operator object
|
|
18483
|
+
const ops = condition;
|
|
18484
|
+
if (ops.not !== undefined) {
|
|
18485
|
+
if (Array.isArray(ops.not)) {
|
|
18486
|
+
// For NOT IN with array: must NOT have a link with value in the array
|
|
18487
|
+
const formattedValues = ops.not.map(v => this.formatSurrealValue(v)).join(', ');
|
|
18488
|
+
conditions.push(`count(->link[WHERE perspective = $perspective AND predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) = 0`);
|
|
18489
|
+
}
|
|
18490
|
+
else {
|
|
18491
|
+
// For NOT with single value: must NOT have this value
|
|
18492
|
+
conditions.push(`count(->link[WHERE perspective = $perspective AND predicate = '${predicate}' AND ${targetField} = ${this.formatSurrealValue(ops.not)}]) = 0`);
|
|
18493
|
+
}
|
|
18494
|
+
}
|
|
18495
|
+
// Note: gt, gte, lt, lte, between, contains operators are filtered in JavaScript
|
|
18496
|
+
// post-query because fn::parse_literal() comparisons in SurrealDB
|
|
18497
|
+
// don't work reliably with numeric comparisons.
|
|
18498
|
+
// These are handled in instancesFromSurrealResult along with author/timestamp filtering.
|
|
18499
|
+
// However, we still need to ensure the property exists
|
|
18500
|
+
const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
|
|
18501
|
+
ops.lt !== undefined || ops.lte !== undefined ||
|
|
18502
|
+
ops.between !== undefined || ops.contains !== undefined;
|
|
18503
|
+
if (hasComparisonOps) {
|
|
18504
|
+
// Ensure we only get nodes that have this property
|
|
18505
|
+
conditions.push(`count(->link[WHERE perspective = $perspective AND predicate = '${predicate}']) > 0`);
|
|
18506
|
+
}
|
|
18507
|
+
}
|
|
18508
|
+
else {
|
|
18509
|
+
// Simple equality
|
|
18510
|
+
conditions.push(`count(->link[WHERE perspective = $perspective AND predicate = '${predicate}' AND ${targetField} = ${this.formatSurrealValue(condition)}]) > 0`);
|
|
18511
|
+
}
|
|
18512
|
+
}
|
|
18513
|
+
}
|
|
18514
|
+
return conditions.join(' AND ');
|
|
18515
|
+
}
|
|
18516
|
+
/**
|
|
18517
|
+
* Builds the WHERE clause for SurrealQL queries.
|
|
18518
|
+
*
|
|
18519
|
+
* @description
|
|
18520
|
+
* Translates the where conditions from the Query object into SurrealQL WHERE clause fragments.
|
|
18521
|
+
* For each property filter, generates a subquery that checks for links with the appropriate
|
|
18522
|
+
* predicate and target value.
|
|
18523
|
+
*
|
|
18524
|
+
* Handles several condition types:
|
|
18525
|
+
* - Simple equality: `{ name: "Pasta" }` → subquery checking for predicate and target match
|
|
18526
|
+
* - Arrays (IN clause): `{ name: ["Pasta", "Pizza"] }` → target IN [...]
|
|
18527
|
+
* - Operators: `{ rating: { gt: 4 } }` → target > '4'
|
|
18528
|
+
* - gt, gte, lt, lte: comparison operators
|
|
18529
|
+
* - not: negation (single value or array)
|
|
18530
|
+
* - between: range check
|
|
18531
|
+
* - contains: substring/element check (uses SurrealQL CONTAINS)
|
|
18532
|
+
* - Special fields: base, author, timestamp are accessed directly, not via subqueries
|
|
18533
|
+
*
|
|
18534
|
+
* All conditions are joined with AND.
|
|
18535
|
+
*
|
|
18536
|
+
* @param metadata - Model metadata containing property predicates
|
|
18537
|
+
* @param where - Where conditions from the query
|
|
18538
|
+
* @returns WHERE clause string (without the "WHERE" keyword), or empty string if no conditions
|
|
18539
|
+
*
|
|
18540
|
+
* @private
|
|
18541
|
+
*/
|
|
18542
|
+
static buildSurrealWhereClause(metadata, where) {
|
|
18543
|
+
if (!where)
|
|
18544
|
+
return '';
|
|
18545
|
+
const conditions = [];
|
|
18546
|
+
for (const [propertyName, condition] of Object.entries(where)) {
|
|
18547
|
+
// Check if this is a special field (base, author, timestamp)
|
|
18548
|
+
// Note: author and timestamp filtering is done in JavaScript after GROUP BY
|
|
18549
|
+
// because they need to be computed from the grouped links first
|
|
18550
|
+
const isSpecial = ['base', 'author', 'timestamp'].includes(propertyName);
|
|
18551
|
+
if (isSpecial) {
|
|
18552
|
+
// Skip author and timestamp - they'll be filtered in JavaScript
|
|
18553
|
+
// Only handle 'base' (which maps to 'source') here
|
|
18554
|
+
if (propertyName === 'author' || propertyName === 'timestamp') {
|
|
18555
|
+
continue; // Skip - will be filtered post-query
|
|
18556
|
+
}
|
|
18557
|
+
const columnName = 'source'; // base maps to source
|
|
18558
|
+
// Handle base/source field directly
|
|
18559
|
+
if (Array.isArray(condition)) {
|
|
18560
|
+
// Array values (IN clause)
|
|
18561
|
+
const formattedValues = condition.map(v => this.formatSurrealValue(v)).join(', ');
|
|
18562
|
+
conditions.push(`${columnName} IN [${formattedValues}]`);
|
|
18563
|
+
}
|
|
18564
|
+
else if (typeof condition === 'object' && condition !== null) {
|
|
18565
|
+
// Operator object
|
|
18566
|
+
const ops = condition;
|
|
18567
|
+
if (ops.not !== undefined) {
|
|
18568
|
+
if (Array.isArray(ops.not)) {
|
|
18569
|
+
const formattedValues = ops.not.map(v => this.formatSurrealValue(v)).join(', ');
|
|
18570
|
+
conditions.push(`${columnName} NOT IN [${formattedValues}]`);
|
|
18571
|
+
}
|
|
18572
|
+
else {
|
|
18573
|
+
conditions.push(`${columnName} != ${this.formatSurrealValue(ops.not)}`);
|
|
18574
|
+
}
|
|
18575
|
+
}
|
|
18576
|
+
if (ops.between !== undefined && Array.isArray(ops.between) && ops.between.length === 2) {
|
|
18577
|
+
conditions.push(`${columnName} >= ${this.formatSurrealValue(ops.between[0])} AND ${columnName} <= ${this.formatSurrealValue(ops.between[1])}`);
|
|
18578
|
+
}
|
|
18579
|
+
if (ops.gt !== undefined) {
|
|
18580
|
+
conditions.push(`${columnName} > ${this.formatSurrealValue(ops.gt)}`);
|
|
18581
|
+
}
|
|
18582
|
+
if (ops.gte !== undefined) {
|
|
18583
|
+
conditions.push(`${columnName} >= ${this.formatSurrealValue(ops.gte)}`);
|
|
18584
|
+
}
|
|
18585
|
+
if (ops.lt !== undefined) {
|
|
18586
|
+
conditions.push(`${columnName} < ${this.formatSurrealValue(ops.lt)}`);
|
|
18587
|
+
}
|
|
18588
|
+
if (ops.lte !== undefined) {
|
|
18589
|
+
conditions.push(`${columnName} <= ${this.formatSurrealValue(ops.lte)}`);
|
|
18590
|
+
}
|
|
18591
|
+
if (ops.contains !== undefined) {
|
|
18592
|
+
conditions.push(`${columnName} CONTAINS ${this.formatSurrealValue(ops.contains)}`);
|
|
18593
|
+
}
|
|
18594
|
+
}
|
|
18595
|
+
else {
|
|
18596
|
+
// Simple equality
|
|
18597
|
+
conditions.push(`${columnName} = ${this.formatSurrealValue(condition)}`);
|
|
18598
|
+
}
|
|
18599
|
+
}
|
|
18600
|
+
else {
|
|
18601
|
+
// Handle regular properties via subqueries
|
|
18602
|
+
const propMeta = metadata.properties[propertyName];
|
|
18603
|
+
if (!propMeta)
|
|
18604
|
+
continue; // Skip if property not found in metadata
|
|
18605
|
+
const predicate = propMeta.predicate;
|
|
18606
|
+
// Use fn::parse_literal() for properties with resolveLanguage
|
|
18607
|
+
const targetField = propMeta.resolveLanguage === 'literal' ? 'fn::parse_literal(target)' : 'target';
|
|
18608
|
+
if (Array.isArray(condition)) {
|
|
18609
|
+
// Array values (IN clause)
|
|
18610
|
+
const formattedValues = condition.map(v => this.formatSurrealValue(v)).join(', ');
|
|
18611
|
+
conditions.push(`source IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}])`);
|
|
18612
|
+
}
|
|
18613
|
+
else if (typeof condition === 'object' && condition !== null) {
|
|
18614
|
+
// Operator object
|
|
18615
|
+
const ops = condition;
|
|
18616
|
+
if (ops.not !== undefined) {
|
|
18617
|
+
if (Array.isArray(ops.not)) {
|
|
18618
|
+
// For NOT IN with array: exclude sources that HAVE a value in the array
|
|
18619
|
+
const formattedValues = ops.not.map(v => this.formatSurrealValue(v)).join(', ');
|
|
18620
|
+
conditions.push(`source NOT IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}])`);
|
|
18621
|
+
}
|
|
18622
|
+
else {
|
|
18623
|
+
// For NOT with single value: exclude sources that HAVE this value
|
|
18624
|
+
conditions.push(`source NOT IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}' AND ${targetField} = ${this.formatSurrealValue(ops.not)})`);
|
|
18625
|
+
}
|
|
18626
|
+
}
|
|
18627
|
+
// Note: gt, gte, lt, lte, between, contains operators are filtered in JavaScript
|
|
18628
|
+
// post-query because fn::parse_literal() comparisons in SurrealDB subqueries
|
|
18629
|
+
// don't work reliably with numeric comparisons.
|
|
18630
|
+
// These are handled in instancesFromSurrealResult along with author/timestamp filtering.
|
|
18631
|
+
// However, we still need to ensure the property exists by filtering on the predicate
|
|
18632
|
+
const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
|
|
18633
|
+
ops.lt !== undefined || ops.lte !== undefined ||
|
|
18634
|
+
ops.between !== undefined || ops.contains !== undefined;
|
|
18635
|
+
if (hasComparisonOps) {
|
|
18636
|
+
// Ensure we only get instances that have this property
|
|
18637
|
+
conditions.push(`source IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}')`);
|
|
18638
|
+
}
|
|
18639
|
+
}
|
|
18640
|
+
else {
|
|
18641
|
+
// Simple equality
|
|
18642
|
+
conditions.push(`source IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}' AND ${targetField} = ${this.formatSurrealValue(condition)})`);
|
|
18643
|
+
}
|
|
18644
|
+
}
|
|
18645
|
+
}
|
|
18646
|
+
return conditions.join(' AND ');
|
|
18647
|
+
}
|
|
18648
|
+
/**
|
|
18649
|
+
* Builds the SELECT fields for SurrealQL queries.
|
|
18650
|
+
*
|
|
18651
|
+
* @description
|
|
18652
|
+
* Generates the field list for the SELECT clause, resolving properties and collections
|
|
18653
|
+
* via subqueries. Each property is fetched with a subquery that finds the link with the
|
|
18654
|
+
* appropriate predicate and returns its target. Collections are similar but don't use LIMIT 1.
|
|
18655
|
+
*
|
|
18656
|
+
* Field types:
|
|
18657
|
+
* - Properties: `(SELECT VALUE target FROM link WHERE source = $parent.base AND predicate = 'X' LIMIT 1) AS propName`
|
|
18658
|
+
* - Collections: `(SELECT VALUE target FROM link WHERE source = $parent.base AND predicate = 'X') AS collName`
|
|
18659
|
+
* - Author/Timestamp: Always included to provide metadata about each instance
|
|
18660
|
+
*
|
|
18661
|
+
* If properties or collections arrays are provided, only those fields are included.
|
|
18662
|
+
* Otherwise, all properties/collections from metadata are included.
|
|
18663
|
+
*
|
|
18664
|
+
* @param metadata - Model metadata containing property and collection predicates
|
|
18665
|
+
* @param properties - Optional array of property names to include (default: all)
|
|
18666
|
+
* @param collections - Optional array of collection names to include (default: all)
|
|
18667
|
+
* @returns Comma-separated SELECT field list
|
|
18668
|
+
*
|
|
18669
|
+
* @private
|
|
18670
|
+
*/
|
|
18671
|
+
static buildSurrealSelectFields(metadata, properties, collections) {
|
|
18672
|
+
const fields = [];
|
|
18673
|
+
// Determine properties to fetch
|
|
18674
|
+
const propsToFetch = properties || Object.keys(metadata.properties);
|
|
18675
|
+
for (const propName of propsToFetch) {
|
|
18676
|
+
const propMeta = metadata.properties[propName];
|
|
18677
|
+
if (!propMeta)
|
|
18678
|
+
continue; // Skip if not found
|
|
18679
|
+
// Reference source directly since we're selecting from link table
|
|
18680
|
+
fields.push(`(SELECT VALUE target FROM link WHERE source = source AND predicate = '${propMeta.predicate}' LIMIT 1) AS ${propName}`);
|
|
18681
|
+
}
|
|
18682
|
+
// Determine collections to fetch
|
|
18683
|
+
const collsToFetch = collections || Object.keys(metadata.collections);
|
|
18684
|
+
for (const collName of collsToFetch) {
|
|
18685
|
+
const collMeta = metadata.collections[collName];
|
|
18686
|
+
if (!collMeta)
|
|
18687
|
+
continue; // Skip if not found
|
|
18688
|
+
// Reference source directly since we're selecting from link table
|
|
18689
|
+
fields.push(`(SELECT VALUE target FROM link WHERE source = source AND predicate = '${collMeta.predicate}') AS ${collName}`);
|
|
18690
|
+
}
|
|
18691
|
+
// Always add author and timestamp fields
|
|
18692
|
+
fields.push(`(SELECT VALUE author FROM link WHERE source = source LIMIT 1) AS author`);
|
|
18693
|
+
fields.push(`(SELECT VALUE timestamp FROM link WHERE source = source LIMIT 1) AS timestamp`);
|
|
18694
|
+
return fields.join(',\n ');
|
|
18695
|
+
}
|
|
18696
|
+
/**
|
|
18697
|
+
* Builds the SELECT fields for SurrealQL queries using aggregation functions.
|
|
18698
|
+
* Compatible with GROUP BY source queries.
|
|
18699
|
+
*
|
|
18700
|
+
* @private
|
|
18701
|
+
*/
|
|
18702
|
+
static buildSurrealSelectFieldsWithAggregation(metadata, properties, collections) {
|
|
18703
|
+
const fields = [];
|
|
18704
|
+
// Determine properties to fetch
|
|
18705
|
+
const propsToFetch = properties || Object.keys(metadata.properties);
|
|
18706
|
+
for (const propName of propsToFetch) {
|
|
18707
|
+
const propMeta = metadata.properties[propName];
|
|
18708
|
+
if (!propMeta)
|
|
18709
|
+
continue; // Skip if not found
|
|
18710
|
+
// Use array::first to get the first target value for this predicate
|
|
18711
|
+
fields.push(`array::first(target[WHERE predicate = '${propMeta.predicate}']) AS ${propName}`);
|
|
18712
|
+
}
|
|
18713
|
+
// Determine collections to fetch
|
|
18714
|
+
const collsToFetch = collections || Object.keys(metadata.collections);
|
|
18715
|
+
for (const collName of collsToFetch) {
|
|
18716
|
+
const collMeta = metadata.collections[collName];
|
|
18717
|
+
if (!collMeta)
|
|
18718
|
+
continue; // Skip if not found
|
|
18719
|
+
// Use array filtering to get all target values for this predicate
|
|
18720
|
+
fields.push(`target[WHERE predicate = '${collMeta.predicate}'] AS ${collName}`);
|
|
18721
|
+
}
|
|
18722
|
+
// Always add author and timestamp fields using array::first
|
|
18723
|
+
fields.push(`array::first(author) AS author`);
|
|
18724
|
+
fields.push(`array::first(timestamp) AS timestamp`);
|
|
18725
|
+
return fields.join(',\n ');
|
|
18726
|
+
}
|
|
18727
|
+
/**
|
|
18728
|
+
* Formats a value for use in SurrealQL queries.
|
|
18729
|
+
*
|
|
18730
|
+
* @description
|
|
18731
|
+
* Handles different value types:
|
|
18732
|
+
* - Strings: Wrapped in single quotes with backslash-escaped special characters
|
|
18733
|
+
* - Numbers/booleans: Converted to string
|
|
18734
|
+
* - Arrays: Recursively formatted and wrapped in brackets
|
|
18735
|
+
*
|
|
18736
|
+
* @param value - The value to format
|
|
18737
|
+
* @returns Formatted value string ready for SurrealQL
|
|
18738
|
+
*
|
|
18739
|
+
* @private
|
|
18740
|
+
*/
|
|
18741
|
+
static formatSurrealValue(value) {
|
|
18742
|
+
if (typeof value === 'string') {
|
|
18743
|
+
// Escape backslashes first, then single quotes and other special characters
|
|
18744
|
+
const escaped = value
|
|
18745
|
+
.replace(/\\/g, '\\\\') // Backslash -> \\
|
|
18746
|
+
.replace(/'/g, "\\'") // Single quote -> \'
|
|
18747
|
+
.replace(/"/g, '\\"') // Double quote -> \"
|
|
18748
|
+
.replace(/\n/g, '\\n') // Newline -> \n
|
|
18749
|
+
.replace(/\r/g, '\\r') // Carriage return -> \r
|
|
18750
|
+
.replace(/\t/g, '\\t'); // Tab -> \t
|
|
18751
|
+
return `'${escaped}'`;
|
|
18752
|
+
}
|
|
18753
|
+
else if (typeof value === 'number' || typeof value === 'boolean') {
|
|
18754
|
+
return String(value);
|
|
18755
|
+
}
|
|
18756
|
+
else if (Array.isArray(value)) {
|
|
18757
|
+
return `[${value.map(v => this.formatSurrealValue(v)).join(', ')}]`;
|
|
18758
|
+
}
|
|
18759
|
+
else {
|
|
18760
|
+
return String(value);
|
|
18761
|
+
}
|
|
18762
|
+
}
|
|
17945
18763
|
static async instancesFromPrologResult(perspective, query, result) {
|
|
17946
18764
|
if (!result?.[0]?.AllInstances)
|
|
17947
18765
|
return { results: [], totalCount: 0 };
|
|
@@ -17970,19 +18788,339 @@ class Ad4mModel {
|
|
|
17970
18788
|
}));
|
|
17971
18789
|
return { results: allInstances.filter((instance) => instance !== null), totalCount: result[0].TotalCount };
|
|
17972
18790
|
}
|
|
18791
|
+
/**
|
|
18792
|
+
* Converts SurrealDB query results to Ad4mModel instances.
|
|
18793
|
+
*
|
|
18794
|
+
* @param perspective - The perspective context
|
|
18795
|
+
* @param query - The query parameters used
|
|
18796
|
+
* @param result - Array of result objects from SurrealDB
|
|
18797
|
+
* @returns Promise resolving to results with total count
|
|
18798
|
+
*
|
|
18799
|
+
* @internal
|
|
18800
|
+
*/
|
|
18801
|
+
static async instancesFromSurrealResult(perspective, query, result) {
|
|
18802
|
+
if (!result || result.length === 0)
|
|
18803
|
+
return { results: [], totalCount: 0 };
|
|
18804
|
+
const metadata = this.getModelMetadata();
|
|
18805
|
+
const requestedProperties = query?.properties || [];
|
|
18806
|
+
const requestedCollections = query?.collections || [];
|
|
18807
|
+
// The query used GROUP BY with graph traversal, so each row has:
|
|
18808
|
+
// - source: the node ID (e.g., "node:abc123")
|
|
18809
|
+
// - source_uri: the actual URI (the base expression)
|
|
18810
|
+
// - links: array of link objects with {predicate, target, author, timestamp}
|
|
18811
|
+
const instances = [];
|
|
18812
|
+
for (const row of result) {
|
|
18813
|
+
let base;
|
|
18814
|
+
try {
|
|
18815
|
+
// Use source_uri as the base (the actual URI), not the node ID
|
|
18816
|
+
base = row.source_uri;
|
|
18817
|
+
// Skip rows without a source_uri field
|
|
18818
|
+
if (!base) {
|
|
18819
|
+
continue;
|
|
18820
|
+
}
|
|
18821
|
+
const links = row.links || [];
|
|
18822
|
+
const instance = new this(perspective, base);
|
|
18823
|
+
// Track the most recent timestamp and corresponding author
|
|
18824
|
+
let maxTimestamp = null;
|
|
18825
|
+
let latestAuthor = null;
|
|
18826
|
+
// Process each link (track index for collection ordering)
|
|
18827
|
+
for (let linkIndex = 0; linkIndex < links.length; linkIndex++) {
|
|
18828
|
+
const link = links[linkIndex];
|
|
18829
|
+
const predicate = link.predicate;
|
|
18830
|
+
const target = link.target;
|
|
18831
|
+
// Skip 'None' values
|
|
18832
|
+
if (target === 'None')
|
|
18833
|
+
continue;
|
|
18834
|
+
// Track the most recent timestamp and its author
|
|
18835
|
+
if (link.timestamp && (!maxTimestamp || link.timestamp > maxTimestamp)) {
|
|
18836
|
+
maxTimestamp = link.timestamp;
|
|
18837
|
+
latestAuthor = link.author;
|
|
18838
|
+
}
|
|
18839
|
+
// Find matching property
|
|
18840
|
+
let foundProperty = false;
|
|
18841
|
+
for (const [propName, propMeta] of Object.entries(metadata.properties)) {
|
|
18842
|
+
if (propMeta.predicate === predicate) {
|
|
18843
|
+
// For properties, take the first value (or we could use timestamp to get latest)
|
|
18844
|
+
// Note: Empty objects {} are truthy, so we need to check for them explicitly
|
|
18845
|
+
const currentValue = instance[propName];
|
|
18846
|
+
const isEmptyObject = typeof currentValue === 'object' && currentValue !== null && !Array.isArray(currentValue) && Object.keys(currentValue).length === 0;
|
|
18847
|
+
if (!currentValue || currentValue === "" || currentValue === 0 || isEmptyObject) {
|
|
18848
|
+
let convertedValue = target;
|
|
18849
|
+
// Parse literal URLs if property has resolveLanguage
|
|
18850
|
+
if (propMeta.resolveLanguage === 'literal' && typeof target === 'string' && target.startsWith('literal://')) {
|
|
18851
|
+
try {
|
|
18852
|
+
convertedValue = Literal.fromUrl(target).get();
|
|
18853
|
+
if (convertedValue.data !== undefined) {
|
|
18854
|
+
convertedValue = convertedValue.data;
|
|
18855
|
+
}
|
|
18856
|
+
}
|
|
18857
|
+
catch (e) {
|
|
18858
|
+
console.warn(`Failed to parse literal URL for ${propName}:`, e);
|
|
18859
|
+
convertedValue = target; // Fall back to raw value
|
|
18860
|
+
}
|
|
18861
|
+
}
|
|
18862
|
+
else {
|
|
18863
|
+
// Type conversion: check the instance property's current type
|
|
18864
|
+
const expectedType = typeof instance[propName];
|
|
18865
|
+
if (expectedType === 'number' && typeof target === 'string') {
|
|
18866
|
+
convertedValue = Number(target);
|
|
18867
|
+
}
|
|
18868
|
+
else if (expectedType === 'boolean' && typeof target === 'string') {
|
|
18869
|
+
convertedValue = target === 'true' || target === '1';
|
|
18870
|
+
}
|
|
18871
|
+
}
|
|
18872
|
+
// Apply transform function if it exists
|
|
18873
|
+
if (propMeta.transform && typeof propMeta.transform === 'function') {
|
|
18874
|
+
convertedValue = propMeta.transform(convertedValue);
|
|
18875
|
+
}
|
|
18876
|
+
instance[propName] = convertedValue;
|
|
18877
|
+
}
|
|
18878
|
+
foundProperty = true;
|
|
18879
|
+
break;
|
|
18880
|
+
}
|
|
18881
|
+
}
|
|
18882
|
+
// If not a property, check if it's a collection
|
|
18883
|
+
if (!foundProperty) {
|
|
18884
|
+
for (const [collName, collMeta] of Object.entries(metadata.collections)) {
|
|
18885
|
+
if (collMeta.predicate === predicate) {
|
|
18886
|
+
// For collections, accumulate all values with their timestamps and indices for sorting
|
|
18887
|
+
if (!instance[collName]) {
|
|
18888
|
+
instance[collName] = [];
|
|
18889
|
+
}
|
|
18890
|
+
// Initialize timestamp tracking array if not already done
|
|
18891
|
+
const timestampsKey = `__${collName}_timestamps`;
|
|
18892
|
+
const indicesKey = `__${collName}_indices`;
|
|
18893
|
+
if (!instance[timestampsKey]) {
|
|
18894
|
+
instance[timestampsKey] = [];
|
|
18895
|
+
}
|
|
18896
|
+
if (!instance[indicesKey]) {
|
|
18897
|
+
instance[indicesKey] = [];
|
|
18898
|
+
}
|
|
18899
|
+
if (!instance[collName].includes(target)) {
|
|
18900
|
+
instance[collName].push(target);
|
|
18901
|
+
instance[timestampsKey].push(link.timestamp || '');
|
|
18902
|
+
// Track original position in the links array for stable sorting
|
|
18903
|
+
instance[indicesKey].push(linkIndex);
|
|
18904
|
+
}
|
|
18905
|
+
break;
|
|
18906
|
+
}
|
|
18907
|
+
}
|
|
18908
|
+
}
|
|
18909
|
+
}
|
|
18910
|
+
// Set author and timestamp from the most recent link
|
|
18911
|
+
if (latestAuthor && maxTimestamp) {
|
|
18912
|
+
instance.author = latestAuthor;
|
|
18913
|
+
// Convert timestamp to number (milliseconds) if it's an ISO string
|
|
18914
|
+
if (typeof maxTimestamp === 'string' && maxTimestamp.includes('T')) {
|
|
18915
|
+
instance.timestamp = new Date(maxTimestamp).getTime();
|
|
18916
|
+
}
|
|
18917
|
+
else if (typeof maxTimestamp === 'string') {
|
|
18918
|
+
// Try to parse as number string
|
|
18919
|
+
const parsed = parseInt(maxTimestamp, 10);
|
|
18920
|
+
instance.timestamp = isNaN(parsed) ? maxTimestamp : parsed;
|
|
18921
|
+
}
|
|
18922
|
+
else {
|
|
18923
|
+
instance.timestamp = maxTimestamp;
|
|
18924
|
+
}
|
|
18925
|
+
}
|
|
18926
|
+
// Sort collections by timestamp to maintain insertion order
|
|
18927
|
+
for (const [collName, collMeta] of Object.entries(metadata.collections)) {
|
|
18928
|
+
const timestampsKey = `__${collName}_timestamps`;
|
|
18929
|
+
const indicesKey = `__${collName}_indices`;
|
|
18930
|
+
if (instance[collName] && instance[timestampsKey]) {
|
|
18931
|
+
// Create array of [value, timestamp, index] tuples
|
|
18932
|
+
const pairs = instance[collName].map((value, index) => ({
|
|
18933
|
+
value,
|
|
18934
|
+
timestamp: instance[timestampsKey][index] || '',
|
|
18935
|
+
originalIndex: instance[indicesKey]?.[index] ?? index
|
|
18936
|
+
}));
|
|
18937
|
+
// Sort by timestamp first, then by original index for stable sorting
|
|
18938
|
+
pairs.sort((a, b) => {
|
|
18939
|
+
const tsA = String(a.timestamp || '');
|
|
18940
|
+
const tsB = String(b.timestamp || '');
|
|
18941
|
+
const tsCompare = tsA.localeCompare(tsB);
|
|
18942
|
+
if (tsCompare !== 0)
|
|
18943
|
+
return tsCompare;
|
|
18944
|
+
// Use original index as tiebreaker for stable sorting
|
|
18945
|
+
return a.originalIndex - b.originalIndex;
|
|
18946
|
+
});
|
|
18947
|
+
// Replace collection with sorted values
|
|
18948
|
+
instance[collName] = pairs.map(p => p.value);
|
|
18949
|
+
// Clean up temporary arrays
|
|
18950
|
+
delete instance[timestampsKey];
|
|
18951
|
+
delete instance[indicesKey];
|
|
18952
|
+
}
|
|
18953
|
+
}
|
|
18954
|
+
// Filter by requested attributes if specified
|
|
18955
|
+
if (requestedProperties.length > 0 || requestedCollections.length > 0) {
|
|
18956
|
+
const requestedAttributes = [...requestedProperties, ...requestedCollections];
|
|
18957
|
+
Object.keys(instance).forEach((key) => {
|
|
18958
|
+
// Keep only requested attributes, plus always keep timestamp and author
|
|
18959
|
+
if (!requestedAttributes.includes(key) && key !== 'timestamp' && key !== 'author' && key !== 'baseExpression') {
|
|
18960
|
+
delete instance[key];
|
|
18961
|
+
}
|
|
18962
|
+
});
|
|
18963
|
+
}
|
|
18964
|
+
instances.push(instance);
|
|
18965
|
+
}
|
|
18966
|
+
catch (error) {
|
|
18967
|
+
console.error(`Failed to process SurrealDB instance ${base}:`, error);
|
|
18968
|
+
}
|
|
18969
|
+
}
|
|
18970
|
+
// Filter by where conditions that couldn't be filtered in SQL
|
|
18971
|
+
// This includes:
|
|
18972
|
+
// - author/timestamp (computed from grouped links)
|
|
18973
|
+
// - Properties with comparison operators (gt, gte, lt, lte, between, contains)
|
|
18974
|
+
// because fn::parse_literal() comparisons in SurrealDB subqueries don't work reliably
|
|
18975
|
+
let filteredInstances = instances;
|
|
18976
|
+
if (query.where) {
|
|
18977
|
+
filteredInstances = instances.filter(instance => {
|
|
18978
|
+
for (const [propertyName, condition] of Object.entries(query.where)) {
|
|
18979
|
+
// Skip 'base' as it's filtered in SQL
|
|
18980
|
+
if (propertyName === 'base')
|
|
18981
|
+
continue;
|
|
18982
|
+
// For author and timestamp, always filter in JS
|
|
18983
|
+
if (propertyName === 'author' || propertyName === 'timestamp') {
|
|
18984
|
+
if (!this.matchesCondition(instance[propertyName], condition)) {
|
|
18985
|
+
return false;
|
|
18986
|
+
}
|
|
18987
|
+
continue;
|
|
18988
|
+
}
|
|
18989
|
+
// For regular properties, only filter comparison operators in JS
|
|
18990
|
+
// Simple equality and NOT are handled in SQL, but gt/gte/lt/lte/between/contains need JS
|
|
18991
|
+
if (typeof condition === 'object' && condition !== null && !Array.isArray(condition)) {
|
|
18992
|
+
const ops = condition;
|
|
18993
|
+
// Check if any comparison operators are present
|
|
18994
|
+
const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
|
|
18995
|
+
ops.lt !== undefined || ops.lte !== undefined ||
|
|
18996
|
+
ops.between !== undefined || ops.contains !== undefined;
|
|
18997
|
+
if (hasComparisonOps) {
|
|
18998
|
+
if (!this.matchesCondition(instance[propertyName], condition)) {
|
|
18999
|
+
return false;
|
|
19000
|
+
}
|
|
19001
|
+
}
|
|
19002
|
+
}
|
|
19003
|
+
}
|
|
19004
|
+
return true;
|
|
19005
|
+
});
|
|
19006
|
+
}
|
|
19007
|
+
// Apply ordering in JavaScript
|
|
19008
|
+
// If limit/offset is used but no explicit order, default to ordering by timestamp (ASC)
|
|
19009
|
+
// This ensures consistent pagination behavior
|
|
19010
|
+
const effectiveOrder = query.order ||
|
|
19011
|
+
(query.limit !== undefined || query.offset !== undefined ? { timestamp: 'ASC' } : null);
|
|
19012
|
+
if (effectiveOrder) {
|
|
19013
|
+
const orderPropName = Object.keys(effectiveOrder)[0];
|
|
19014
|
+
const orderDirection = Object.values(effectiveOrder)[0];
|
|
19015
|
+
filteredInstances.sort((a, b) => {
|
|
19016
|
+
let aVal = a[orderPropName];
|
|
19017
|
+
let bVal = b[orderPropName];
|
|
19018
|
+
// Handle undefined values - push them to the end
|
|
19019
|
+
if (aVal === undefined && bVal === undefined)
|
|
19020
|
+
return 0;
|
|
19021
|
+
if (aVal === undefined)
|
|
19022
|
+
return orderDirection === 'ASC' ? 1 : -1;
|
|
19023
|
+
if (bVal === undefined)
|
|
19024
|
+
return orderDirection === 'ASC' ? -1 : 1;
|
|
19025
|
+
// Compare values
|
|
19026
|
+
let comparison = 0;
|
|
19027
|
+
if (typeof aVal === 'number' && typeof bVal === 'number') {
|
|
19028
|
+
comparison = aVal - bVal;
|
|
19029
|
+
}
|
|
19030
|
+
else if (typeof aVal === 'string' && typeof bVal === 'string') {
|
|
19031
|
+
comparison = aVal.localeCompare(bVal);
|
|
19032
|
+
}
|
|
19033
|
+
else {
|
|
19034
|
+
// Convert to strings for comparison
|
|
19035
|
+
comparison = String(aVal).localeCompare(String(bVal));
|
|
19036
|
+
}
|
|
19037
|
+
return orderDirection === 'DESC' ? -comparison : comparison;
|
|
19038
|
+
});
|
|
19039
|
+
}
|
|
19040
|
+
// Calculate totalCount BEFORE applying limit/offset
|
|
19041
|
+
const totalCount = filteredInstances.length;
|
|
19042
|
+
// Apply offset and limit in JavaScript
|
|
19043
|
+
let paginatedInstances = filteredInstances;
|
|
19044
|
+
if (query.offset !== undefined || query.limit !== undefined) {
|
|
19045
|
+
const start = query.offset || 0;
|
|
19046
|
+
const end = query.limit ? start + query.limit : undefined;
|
|
19047
|
+
paginatedInstances = filteredInstances.slice(start, end);
|
|
19048
|
+
}
|
|
19049
|
+
return {
|
|
19050
|
+
results: paginatedInstances,
|
|
19051
|
+
totalCount
|
|
19052
|
+
};
|
|
19053
|
+
}
|
|
19054
|
+
/**
|
|
19055
|
+
* Checks if a value matches a condition (for post-query filtering).
|
|
19056
|
+
* @private
|
|
19057
|
+
*/
|
|
19058
|
+
static matchesCondition(value, condition) {
|
|
19059
|
+
// Handle array values (IN clause)
|
|
19060
|
+
if (Array.isArray(condition)) {
|
|
19061
|
+
return condition.includes(value);
|
|
19062
|
+
}
|
|
19063
|
+
// Handle operator object
|
|
19064
|
+
if (typeof condition === 'object' && condition !== null) {
|
|
19065
|
+
const ops = condition;
|
|
19066
|
+
// Special case: 'not' operator (exclusive with other operators)
|
|
19067
|
+
if (ops.not !== undefined) {
|
|
19068
|
+
if (Array.isArray(ops.not)) {
|
|
19069
|
+
return !ops.not.includes(value);
|
|
19070
|
+
}
|
|
19071
|
+
else {
|
|
19072
|
+
return value !== ops.not;
|
|
19073
|
+
}
|
|
19074
|
+
}
|
|
19075
|
+
// Special case: 'between' operator (inclusive range, exclusive with gt/gte/lt/lte)
|
|
19076
|
+
if (ops.between !== undefined && Array.isArray(ops.between) && ops.between.length === 2) {
|
|
19077
|
+
return value >= ops.between[0] && value <= ops.between[1];
|
|
19078
|
+
}
|
|
19079
|
+
// For all other operators (gt, gte, lt, lte, contains), we need to check ALL of them
|
|
19080
|
+
// and return true only if ALL conditions are satisfied
|
|
19081
|
+
let allConditionsMet = true;
|
|
19082
|
+
if (ops.gt !== undefined) {
|
|
19083
|
+
allConditionsMet = allConditionsMet && (value > ops.gt);
|
|
19084
|
+
}
|
|
19085
|
+
if (ops.gte !== undefined) {
|
|
19086
|
+
allConditionsMet = allConditionsMet && (value >= ops.gte);
|
|
19087
|
+
}
|
|
19088
|
+
if (ops.lt !== undefined) {
|
|
19089
|
+
allConditionsMet = allConditionsMet && (value < ops.lt);
|
|
19090
|
+
}
|
|
19091
|
+
if (ops.lte !== undefined) {
|
|
19092
|
+
allConditionsMet = allConditionsMet && (value <= ops.lte);
|
|
19093
|
+
}
|
|
19094
|
+
if (ops.contains !== undefined) {
|
|
19095
|
+
if (typeof value === 'string') {
|
|
19096
|
+
allConditionsMet = allConditionsMet && value.includes(String(ops.contains));
|
|
19097
|
+
}
|
|
19098
|
+
else if (Array.isArray(value)) {
|
|
19099
|
+
allConditionsMet = allConditionsMet && value.includes(ops.contains);
|
|
19100
|
+
}
|
|
19101
|
+
else {
|
|
19102
|
+
allConditionsMet = false;
|
|
19103
|
+
}
|
|
19104
|
+
}
|
|
19105
|
+
return allConditionsMet;
|
|
19106
|
+
}
|
|
19107
|
+
// Simple equality
|
|
19108
|
+
return value === condition;
|
|
19109
|
+
}
|
|
17973
19110
|
/**
|
|
17974
19111
|
* Gets all instances of the model in the perspective that match the query params.
|
|
17975
19112
|
*
|
|
17976
19113
|
* @param perspective - The perspective to search in
|
|
17977
19114
|
* @param query - Optional query parameters to filter results
|
|
19115
|
+
* @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
|
|
17978
19116
|
* @returns Array of matching models
|
|
17979
19117
|
*
|
|
17980
19118
|
* @example
|
|
17981
19119
|
* ```typescript
|
|
17982
|
-
* // Get all recipes
|
|
19120
|
+
* // Get all recipes (uses SurrealDB by default)
|
|
17983
19121
|
* const allRecipes = await Recipe.findAll(perspective);
|
|
17984
19122
|
*
|
|
17985
|
-
* // Get recipes with specific criteria
|
|
19123
|
+
* // Get recipes with specific criteria (uses SurrealDB)
|
|
17986
19124
|
* const recipes = await Recipe.findAll(perspective, {
|
|
17987
19125
|
* where: {
|
|
17988
19126
|
* name: "Pasta",
|
|
@@ -17991,19 +19129,31 @@ class Ad4mModel {
|
|
|
17991
19129
|
* order: { createdAt: "DESC" },
|
|
17992
19130
|
* limit: 10
|
|
17993
19131
|
* });
|
|
19132
|
+
*
|
|
19133
|
+
* // Explicitly use Prolog (legacy, for backward compatibility)
|
|
19134
|
+
* const recipesProlog = await Recipe.findAll(perspective, {}, false);
|
|
17994
19135
|
* ```
|
|
17995
19136
|
*/
|
|
17996
|
-
static async findAll(perspective, query = {}) {
|
|
17997
|
-
|
|
17998
|
-
|
|
17999
|
-
|
|
18000
|
-
|
|
19137
|
+
static async findAll(perspective, query = {}, useSurrealDB = true) {
|
|
19138
|
+
if (useSurrealDB) {
|
|
19139
|
+
const surrealQuery = await this.queryToSurrealQL(perspective, query);
|
|
19140
|
+
const result = await perspective.querySurrealDB(surrealQuery);
|
|
19141
|
+
const { results } = await this.instancesFromSurrealResult(perspective, query, result);
|
|
19142
|
+
return results;
|
|
19143
|
+
}
|
|
19144
|
+
else {
|
|
19145
|
+
const prologQuery = await this.queryToProlog(perspective, query);
|
|
19146
|
+
const result = await perspective.infer(prologQuery);
|
|
19147
|
+
const { results } = await this.instancesFromPrologResult(perspective, query, result);
|
|
19148
|
+
return results;
|
|
19149
|
+
}
|
|
18001
19150
|
}
|
|
18002
19151
|
/**
|
|
18003
19152
|
* Gets all instances with count of total matches without offset & limit applied.
|
|
18004
19153
|
*
|
|
18005
19154
|
* @param perspective - The perspective to search in
|
|
18006
19155
|
* @param query - Optional query parameters to filter results
|
|
19156
|
+
* @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
|
|
18007
19157
|
* @returns Object containing results array and total count
|
|
18008
19158
|
*
|
|
18009
19159
|
* @example
|
|
@@ -18013,12 +19163,22 @@ class Ad4mModel {
|
|
|
18013
19163
|
* limit: 10
|
|
18014
19164
|
* });
|
|
18015
19165
|
* console.log(`Showing 10 of ${totalCount} dessert recipes`);
|
|
19166
|
+
*
|
|
19167
|
+
* // Use Prolog explicitly (legacy)
|
|
19168
|
+
* const { results, totalCount } = await Recipe.findAllAndCount(perspective, {}, false);
|
|
18016
19169
|
* ```
|
|
18017
19170
|
*/
|
|
18018
|
-
static async findAllAndCount(perspective, query = {}) {
|
|
18019
|
-
|
|
18020
|
-
|
|
18021
|
-
|
|
19171
|
+
static async findAllAndCount(perspective, query = {}, useSurrealDB = true) {
|
|
19172
|
+
if (useSurrealDB) {
|
|
19173
|
+
const surrealQuery = await this.queryToSurrealQL(perspective, query);
|
|
19174
|
+
const result = await perspective.querySurrealDB(surrealQuery);
|
|
19175
|
+
return await this.instancesFromSurrealResult(perspective, query, result);
|
|
19176
|
+
}
|
|
19177
|
+
else {
|
|
19178
|
+
const prologQuery = await this.queryToProlog(perspective, query);
|
|
19179
|
+
const result = await perspective.infer(prologQuery);
|
|
19180
|
+
return await this.instancesFromPrologResult(perspective, query, result);
|
|
19181
|
+
}
|
|
18022
19182
|
}
|
|
18023
19183
|
/**
|
|
18024
19184
|
* Helper function for pagination with explicit page size and number.
|
|
@@ -18027,6 +19187,7 @@ class Ad4mModel {
|
|
|
18027
19187
|
* @param pageSize - Number of items per page
|
|
18028
19188
|
* @param pageNumber - Which page to retrieve (1-based)
|
|
18029
19189
|
* @param query - Optional additional query parameters
|
|
19190
|
+
* @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
|
|
18030
19191
|
* @returns Paginated results with metadata
|
|
18031
19192
|
*
|
|
18032
19193
|
* @example
|
|
@@ -18035,14 +19196,25 @@ class Ad4mModel {
|
|
|
18035
19196
|
* where: { category: "Main Course" }
|
|
18036
19197
|
* });
|
|
18037
19198
|
* console.log(`Page ${page.pageNumber} of recipes, ${page.results.length} items`);
|
|
19199
|
+
*
|
|
19200
|
+
* // Use Prolog explicitly (legacy)
|
|
19201
|
+
* const pageProlog = await Recipe.paginate(perspective, 10, 1, {}, false);
|
|
18038
19202
|
* ```
|
|
18039
19203
|
*/
|
|
18040
|
-
static async paginate(perspective, pageSize, pageNumber, query) {
|
|
19204
|
+
static async paginate(perspective, pageSize, pageNumber, query, useSurrealDB = true) {
|
|
18041
19205
|
const paginationQuery = { ...(query || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
|
|
18042
|
-
|
|
18043
|
-
|
|
18044
|
-
|
|
18045
|
-
|
|
19206
|
+
if (useSurrealDB) {
|
|
19207
|
+
const surrealQuery = await this.queryToSurrealQL(perspective, paginationQuery);
|
|
19208
|
+
const result = await perspective.querySurrealDB(surrealQuery);
|
|
19209
|
+
const { results, totalCount } = await this.instancesFromSurrealResult(perspective, paginationQuery, result);
|
|
19210
|
+
return { results, totalCount, pageSize, pageNumber };
|
|
19211
|
+
}
|
|
19212
|
+
else {
|
|
19213
|
+
const prologQuery = await this.queryToProlog(perspective, paginationQuery);
|
|
19214
|
+
const result = await perspective.infer(prologQuery);
|
|
19215
|
+
const { results, totalCount } = await this.instancesFromPrologResult(perspective, paginationQuery, result);
|
|
19216
|
+
return { results, totalCount, pageSize, pageNumber };
|
|
19217
|
+
}
|
|
18046
19218
|
}
|
|
18047
19219
|
static async countQueryToProlog(perspective, query = {}, modelClassName) {
|
|
18048
19220
|
const { source, where } = query;
|
|
@@ -18059,11 +19231,29 @@ class Ad4mModel {
|
|
|
18059
19231
|
`;
|
|
18060
19232
|
return fullQuery;
|
|
18061
19233
|
}
|
|
19234
|
+
/**
|
|
19235
|
+
* Generates a SurrealQL COUNT query for the model.
|
|
19236
|
+
*
|
|
19237
|
+
* @param perspective - The perspective context
|
|
19238
|
+
* @param query - Query parameters to filter the count
|
|
19239
|
+
* @returns SurrealQL COUNT query string
|
|
19240
|
+
*
|
|
19241
|
+
* @private
|
|
19242
|
+
*/
|
|
19243
|
+
static async countQueryToSurrealQL(perspective, query) {
|
|
19244
|
+
// Use the same query as the main query (with GROUP BY), just without LIMIT/OFFSET
|
|
19245
|
+
// We'll count the number of rows returned (one row per source)
|
|
19246
|
+
const countQuery = { ...query };
|
|
19247
|
+
delete countQuery.limit;
|
|
19248
|
+
delete countQuery.offset;
|
|
19249
|
+
return await this.queryToSurrealQL(perspective, countQuery);
|
|
19250
|
+
}
|
|
18062
19251
|
/**
|
|
18063
19252
|
* Gets a count of all matching instances.
|
|
18064
19253
|
*
|
|
18065
19254
|
* @param perspective - The perspective to search in
|
|
18066
19255
|
* @param query - Optional query parameters to filter results
|
|
19256
|
+
* @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
|
|
18067
19257
|
* @returns Total count of matching entities
|
|
18068
19258
|
*
|
|
18069
19259
|
* @example
|
|
@@ -18072,11 +19262,25 @@ class Ad4mModel {
|
|
|
18072
19262
|
* const activeRecipes = await Recipe.count(perspective, {
|
|
18073
19263
|
* where: { status: "active" }
|
|
18074
19264
|
* });
|
|
19265
|
+
*
|
|
19266
|
+
* // Use Prolog explicitly (legacy)
|
|
19267
|
+
* const countProlog = await Recipe.count(perspective, {}, false);
|
|
18075
19268
|
* ```
|
|
18076
19269
|
*/
|
|
18077
|
-
static async count(perspective, query = {}) {
|
|
18078
|
-
|
|
18079
|
-
|
|
19270
|
+
static async count(perspective, query = {}, useSurrealDB = true) {
|
|
19271
|
+
if (useSurrealDB) {
|
|
19272
|
+
const surrealQuery = await this.queryToSurrealQL(perspective, query);
|
|
19273
|
+
const result = await perspective.querySurrealDB(surrealQuery);
|
|
19274
|
+
// Use instancesFromSurrealResult to apply JS-level filtering for advanced where conditions
|
|
19275
|
+
// (e.g., gt, gte, lt, lte, between, contains on properties and author/timestamp)
|
|
19276
|
+
// This ensures count() returns the same number as findAll().length
|
|
19277
|
+
const { totalCount } = await this.instancesFromSurrealResult(perspective, query, result);
|
|
19278
|
+
return totalCount;
|
|
19279
|
+
}
|
|
19280
|
+
else {
|
|
19281
|
+
const result = await perspective.infer(await this.countQueryToProlog(perspective, query));
|
|
19282
|
+
return result?.[0]?.TotalCount || 0;
|
|
19283
|
+
}
|
|
18080
19284
|
}
|
|
18081
19285
|
async setProperty(key, value, batchId) {
|
|
18082
19286
|
const setters = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _Ad4mModel_subjectClassName, "f")}", C), property_setter(C, "${key}", Setter)`);
|
|
@@ -18318,6 +19522,318 @@ class Ad4mModel {
|
|
|
18318
19522
|
static query(perspective, query) {
|
|
18319
19523
|
return new ModelQueryBuilder(perspective, this, query);
|
|
18320
19524
|
}
|
|
19525
|
+
/**
|
|
19526
|
+
* Creates an Ad4mModel class from a JSON Schema definition.
|
|
19527
|
+
*
|
|
19528
|
+
* @description
|
|
19529
|
+
* This method dynamically generates an Ad4mModel subclass from a JSON Schema,
|
|
19530
|
+
* enabling integration with systems that use JSON Schema for type definitions.
|
|
19531
|
+
*
|
|
19532
|
+
* The method follows a cascading approach for determining predicates:
|
|
19533
|
+
* 1. Explicit configuration in options parameter (highest precedence)
|
|
19534
|
+
* 2. x-ad4m metadata in the JSON Schema
|
|
19535
|
+
* 3. Inference from schema title and property names
|
|
19536
|
+
* 4. Error if no namespace can be determined
|
|
19537
|
+
*
|
|
19538
|
+
* @example
|
|
19539
|
+
* ```typescript
|
|
19540
|
+
* // With explicit configuration
|
|
19541
|
+
* const PersonClass = Ad4mModel.fromJSONSchema(schema, {
|
|
19542
|
+
* name: "Person",
|
|
19543
|
+
* namespace: "person://",
|
|
19544
|
+
* resolveLanguage: "literal"
|
|
19545
|
+
* });
|
|
19546
|
+
*
|
|
19547
|
+
* // With property mapping
|
|
19548
|
+
* const ContactClass = Ad4mModel.fromJSONSchema(schema, {
|
|
19549
|
+
* name: "Contact",
|
|
19550
|
+
* namespace: "contact://",
|
|
19551
|
+
* propertyMapping: {
|
|
19552
|
+
* "name": "foaf://name",
|
|
19553
|
+
* "email": "foaf://mbox"
|
|
19554
|
+
* }
|
|
19555
|
+
* });
|
|
19556
|
+
*
|
|
19557
|
+
* // With x-ad4m metadata in schema
|
|
19558
|
+
* const schema = {
|
|
19559
|
+
* "title": "Product",
|
|
19560
|
+
* "x-ad4m": { "namespace": "product://" },
|
|
19561
|
+
* "properties": {
|
|
19562
|
+
* "name": {
|
|
19563
|
+
* "type": "string",
|
|
19564
|
+
* "x-ad4m": { "through": "product://title" }
|
|
19565
|
+
* }
|
|
19566
|
+
* }
|
|
19567
|
+
* };
|
|
19568
|
+
* const ProductClass = Ad4mModel.fromJSONSchema(schema, { name: "Product" });
|
|
19569
|
+
* ```
|
|
19570
|
+
*
|
|
19571
|
+
* @param schema - JSON Schema definition
|
|
19572
|
+
* @param options - Configuration options
|
|
19573
|
+
* @returns Generated Ad4mModel subclass
|
|
19574
|
+
* @throws Error when namespace cannot be inferred
|
|
19575
|
+
*/
|
|
19576
|
+
static fromJSONSchema(schema, options) {
|
|
19577
|
+
// Disallow top-level "author" property since Ad4mModel provides it implicitly via link authorship
|
|
19578
|
+
if (schema?.properties && Object.prototype.hasOwnProperty.call(schema.properties, "author")) {
|
|
19579
|
+
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").');
|
|
19580
|
+
}
|
|
19581
|
+
// Determine namespace with cascading precedence
|
|
19582
|
+
const namespace = this.determineNamespace(schema, options);
|
|
19583
|
+
// Create the dynamic class
|
|
19584
|
+
const DynamicModelClass = class extends Ad4mModel {
|
|
19585
|
+
};
|
|
19586
|
+
// Set up class metadata
|
|
19587
|
+
if (!options.name || options.name.trim() === '') {
|
|
19588
|
+
throw new Error("options.name is required and cannot be empty");
|
|
19589
|
+
}
|
|
19590
|
+
DynamicModelClass.className = options.name;
|
|
19591
|
+
DynamicModelClass.prototype.className = options.name;
|
|
19592
|
+
// Generate properties and collections metadata
|
|
19593
|
+
const properties = {};
|
|
19594
|
+
const collections = {};
|
|
19595
|
+
if (schema.properties) {
|
|
19596
|
+
for (const [propertyName, propertySchema] of Object.entries(schema.properties)) {
|
|
19597
|
+
const predicate = this.determinePredicate(schema, propertyName, propertySchema, namespace, options);
|
|
19598
|
+
const isRequired = schema.required?.includes(propertyName) || false;
|
|
19599
|
+
const propertyType = normalizeSchemaType(propertySchema.type);
|
|
19600
|
+
const isArray = isArrayType(propertySchema);
|
|
19601
|
+
if (isArray) {
|
|
19602
|
+
// Handle arrays as collections
|
|
19603
|
+
// Store the singular form as the collection key since SDNA generation expects singular
|
|
19604
|
+
collections[propertyName] = {
|
|
19605
|
+
through: predicate,
|
|
19606
|
+
local: this.getPropertyOption(propertyName, propertySchema, options, 'local')
|
|
19607
|
+
};
|
|
19608
|
+
// Define the property on prototype
|
|
19609
|
+
Object.defineProperty(DynamicModelClass.prototype, propertyName, {
|
|
19610
|
+
configurable: true,
|
|
19611
|
+
writable: true,
|
|
19612
|
+
value: []
|
|
19613
|
+
});
|
|
19614
|
+
// Add collection methods
|
|
19615
|
+
const adderName = `add${capitalize(propertyName)}`;
|
|
19616
|
+
const removerName = `remove${capitalize(propertyName)}`;
|
|
19617
|
+
const setterName = `setCollection${capitalize(propertyName)}`;
|
|
19618
|
+
DynamicModelClass.prototype[adderName] = function () {
|
|
19619
|
+
// Placeholder function for SDNA generation
|
|
19620
|
+
};
|
|
19621
|
+
DynamicModelClass.prototype[removerName] = function () {
|
|
19622
|
+
// Placeholder function for SDNA generation
|
|
19623
|
+
};
|
|
19624
|
+
DynamicModelClass.prototype[setterName] = function () {
|
|
19625
|
+
// Placeholder function for SDNA generation
|
|
19626
|
+
};
|
|
19627
|
+
}
|
|
19628
|
+
else {
|
|
19629
|
+
// Handle regular properties
|
|
19630
|
+
let resolveLanguage = this.getPropertyOption(propertyName, propertySchema, options, 'resolveLanguage');
|
|
19631
|
+
// If no specific resolveLanguage for this property, use the global one
|
|
19632
|
+
if (!resolveLanguage && options.resolveLanguage) {
|
|
19633
|
+
resolveLanguage = options.resolveLanguage;
|
|
19634
|
+
}
|
|
19635
|
+
const local = this.getPropertyOption(propertyName, propertySchema, options, 'local');
|
|
19636
|
+
const writable = this.getPropertyOption(propertyName, propertySchema, options, 'writable', true);
|
|
19637
|
+
let initial = this.getPropertyOption(propertyName, propertySchema, options, 'initial');
|
|
19638
|
+
// Handle nested objects by serializing to JSON
|
|
19639
|
+
if (isObjectType(propertySchema) && !resolveLanguage) {
|
|
19640
|
+
resolveLanguage = 'literal';
|
|
19641
|
+
console.warn(`Property "${propertyName}" is an object type. It will be stored as JSON. Consider flattening complex objects for better semantic querying.`);
|
|
19642
|
+
}
|
|
19643
|
+
// Ensure numeric properties use literal language for correct typing
|
|
19644
|
+
if ((resolveLanguage === undefined || resolveLanguage === null) && isNumericType(propertySchema)) {
|
|
19645
|
+
resolveLanguage = 'literal';
|
|
19646
|
+
}
|
|
19647
|
+
// If property is required, ensure it has an initial value
|
|
19648
|
+
if (isRequired && !initial) {
|
|
19649
|
+
if (isObjectType(propertySchema)) {
|
|
19650
|
+
initial = 'literal://json:{}';
|
|
19651
|
+
}
|
|
19652
|
+
else {
|
|
19653
|
+
initial = "ad4m://undefined";
|
|
19654
|
+
}
|
|
19655
|
+
}
|
|
19656
|
+
properties[propertyName] = {
|
|
19657
|
+
through: predicate,
|
|
19658
|
+
required: isRequired,
|
|
19659
|
+
writable: writable,
|
|
19660
|
+
...(resolveLanguage && { resolveLanguage }),
|
|
19661
|
+
...(local !== undefined && { local }),
|
|
19662
|
+
...(initial && { initial })
|
|
19663
|
+
};
|
|
19664
|
+
// Define the property on prototype
|
|
19665
|
+
Object.defineProperty(DynamicModelClass.prototype, propertyName, {
|
|
19666
|
+
configurable: true,
|
|
19667
|
+
writable: true,
|
|
19668
|
+
value: this.getDefaultValueForType(propertyType)
|
|
19669
|
+
});
|
|
19670
|
+
// Add setter function if writable
|
|
19671
|
+
if (writable) {
|
|
19672
|
+
const setterName = propertyNameToSetterName(propertyName);
|
|
19673
|
+
DynamicModelClass.prototype[setterName] = function () {
|
|
19674
|
+
// This is a placeholder function that the SDNA generation looks for
|
|
19675
|
+
// The actual setter logic is handled by the Ad4mModel base class
|
|
19676
|
+
};
|
|
19677
|
+
}
|
|
19678
|
+
}
|
|
19679
|
+
}
|
|
19680
|
+
}
|
|
19681
|
+
// Validate that at least one property has an initial value (needed for valid SDNA constructor)
|
|
19682
|
+
// Collections don't create constructor actions, only properties with initial values do
|
|
19683
|
+
const hasPropertyWithInitial = Object.values(properties).some((prop) => prop.initial);
|
|
19684
|
+
if (!hasPropertyWithInitial) {
|
|
19685
|
+
// If no properties have initial values, add a type identifier automatically
|
|
19686
|
+
const typeProperty = `ad4m://type`;
|
|
19687
|
+
let typeValue;
|
|
19688
|
+
if (namespace.includes('://')) {
|
|
19689
|
+
const [scheme, rest] = namespace.split('://');
|
|
19690
|
+
const path = (rest || '').replace(/\/+$/, '');
|
|
19691
|
+
if (path) {
|
|
19692
|
+
typeValue = `${scheme}://${path}/instance`;
|
|
19693
|
+
}
|
|
19694
|
+
else {
|
|
19695
|
+
typeValue = `${scheme}://instance`;
|
|
19696
|
+
}
|
|
19697
|
+
}
|
|
19698
|
+
else {
|
|
19699
|
+
const path = namespace.replace(/\/+$/, '');
|
|
19700
|
+
typeValue = `${path}/instance`;
|
|
19701
|
+
}
|
|
19702
|
+
properties['__ad4m_type'] = {
|
|
19703
|
+
through: typeProperty,
|
|
19704
|
+
required: true,
|
|
19705
|
+
writable: false,
|
|
19706
|
+
initial: typeValue,
|
|
19707
|
+
flag: true
|
|
19708
|
+
};
|
|
19709
|
+
// Add the type property to the prototype
|
|
19710
|
+
Object.defineProperty(DynamicModelClass.prototype, '__ad4m_type', {
|
|
19711
|
+
configurable: true,
|
|
19712
|
+
writable: false,
|
|
19713
|
+
value: typeValue
|
|
19714
|
+
});
|
|
19715
|
+
console.warn(`No properties with initial values found. Added automatic type flag: ${typeProperty} = ${typeValue}`);
|
|
19716
|
+
}
|
|
19717
|
+
// Attach metadata to prototype
|
|
19718
|
+
DynamicModelClass.prototype.__properties = properties;
|
|
19719
|
+
DynamicModelClass.prototype.__collections = collections;
|
|
19720
|
+
// Store the JSON schema and options on the prototype for potential fallback use by getModelMetadata()
|
|
19721
|
+
DynamicModelClass.prototype.__jsonSchema = schema;
|
|
19722
|
+
DynamicModelClass.prototype.__jsonSchemaOptions = options;
|
|
19723
|
+
// Apply the ModelOptions decorator to set up the generateSDNA method
|
|
19724
|
+
const ModelOptionsDecorator = ModelOptions({ name: options.name });
|
|
19725
|
+
ModelOptionsDecorator(DynamicModelClass);
|
|
19726
|
+
return DynamicModelClass;
|
|
19727
|
+
}
|
|
19728
|
+
/**
|
|
19729
|
+
* Determines the namespace for predicates using cascading precedence
|
|
19730
|
+
*/
|
|
19731
|
+
static determineNamespace(schema, options) {
|
|
19732
|
+
// 1. Explicit namespace in options (highest precedence)
|
|
19733
|
+
if (options.namespace) {
|
|
19734
|
+
return options.namespace;
|
|
19735
|
+
}
|
|
19736
|
+
// 2. x-ad4m metadata in schema
|
|
19737
|
+
if (schema["x-ad4m"]?.namespace) {
|
|
19738
|
+
return schema["x-ad4m"].namespace;
|
|
19739
|
+
}
|
|
19740
|
+
// 3. Infer from schema title
|
|
19741
|
+
if (schema.title) {
|
|
19742
|
+
return `${schema.title.toLowerCase()}://`;
|
|
19743
|
+
}
|
|
19744
|
+
// 4. Try to extract from $id if it's a URL
|
|
19745
|
+
if (schema.$id) {
|
|
19746
|
+
try {
|
|
19747
|
+
const url = new URL(schema.$id);
|
|
19748
|
+
const pathParts = url.pathname.split('/').filter(p => p);
|
|
19749
|
+
if (pathParts.length > 0) {
|
|
19750
|
+
const lastPart = pathParts[pathParts.length - 1];
|
|
19751
|
+
const baseName = lastPart.replace(/\.schema\.json$/, '').replace(/\.json$/, '');
|
|
19752
|
+
return `${baseName.toLowerCase()}://`;
|
|
19753
|
+
}
|
|
19754
|
+
}
|
|
19755
|
+
catch {
|
|
19756
|
+
// If $id is not a valid URL, continue to error
|
|
19757
|
+
}
|
|
19758
|
+
}
|
|
19759
|
+
// 5. Error if no namespace can be determined
|
|
19760
|
+
throw new Error(`Cannot infer namespace for JSON Schema. Please provide one of:
|
|
19761
|
+
- options.namespace
|
|
19762
|
+
- schema["x-ad4m"].namespace
|
|
19763
|
+
- schema.title
|
|
19764
|
+
- valid schema.$id`);
|
|
19765
|
+
}
|
|
19766
|
+
/**
|
|
19767
|
+
* Determines the predicate for a specific property using cascading precedence
|
|
19768
|
+
*/
|
|
19769
|
+
static determinePredicate(schema, propertyName, propertySchema, namespace, options) {
|
|
19770
|
+
// 1. Explicit property mapping (highest precedence)
|
|
19771
|
+
if (options.propertyMapping?.[propertyName]) {
|
|
19772
|
+
return options.propertyMapping[propertyName];
|
|
19773
|
+
}
|
|
19774
|
+
// 2. x-ad4m metadata in property schema
|
|
19775
|
+
if (propertySchema["x-ad4m"]?.through) {
|
|
19776
|
+
return propertySchema["x-ad4m"].through;
|
|
19777
|
+
}
|
|
19778
|
+
// 3. Generate from namespace + property name
|
|
19779
|
+
if (options.predicateTemplate) {
|
|
19780
|
+
const normalizedNs = normalizeNamespaceString(namespace);
|
|
19781
|
+
const [scheme, rest] = normalizedNs.includes('://') ? normalizedNs.split('://') : ['', normalizedNs];
|
|
19782
|
+
const nsNoScheme = rest || '';
|
|
19783
|
+
return options.predicateTemplate
|
|
19784
|
+
.replace('${namespace}', nsNoScheme)
|
|
19785
|
+
.replace('${scheme}', scheme)
|
|
19786
|
+
.replace('${ns}', nsNoScheme)
|
|
19787
|
+
.replace('${title}', schema.title || '')
|
|
19788
|
+
.replace('${property}', propertyName);
|
|
19789
|
+
}
|
|
19790
|
+
// 4. Custom predicate generator
|
|
19791
|
+
if (options.predicateGenerator) {
|
|
19792
|
+
return options.predicateGenerator(schema.title || '', propertyName);
|
|
19793
|
+
}
|
|
19794
|
+
// 5. Default: namespace + property name
|
|
19795
|
+
const normalizedNs = normalizeNamespaceString(namespace);
|
|
19796
|
+
if (normalizedNs.includes('://')) {
|
|
19797
|
+
// For namespaces like "product://", append property directly
|
|
19798
|
+
return `${normalizedNs}${propertyName}`;
|
|
19799
|
+
}
|
|
19800
|
+
else {
|
|
19801
|
+
return `${normalizedNs}://${propertyName}`;
|
|
19802
|
+
}
|
|
19803
|
+
}
|
|
19804
|
+
/**
|
|
19805
|
+
* Gets property-specific options using cascading precedence
|
|
19806
|
+
*/
|
|
19807
|
+
static getPropertyOption(propertyName, propertySchema, options, optionName, defaultValue) {
|
|
19808
|
+
// 1. Property-specific options
|
|
19809
|
+
if (options.propertyOptions?.[propertyName]?.[optionName] !== undefined) {
|
|
19810
|
+
return options.propertyOptions[propertyName][optionName];
|
|
19811
|
+
}
|
|
19812
|
+
// 2. x-ad4m metadata in property
|
|
19813
|
+
if (propertySchema["x-ad4m"]?.[optionName] !== undefined) {
|
|
19814
|
+
return propertySchema["x-ad4m"][optionName];
|
|
19815
|
+
}
|
|
19816
|
+
// 3. Global option
|
|
19817
|
+
if (options[optionName] !== undefined) {
|
|
19818
|
+
return options[optionName];
|
|
19819
|
+
}
|
|
19820
|
+
// 4. Default value
|
|
19821
|
+
return defaultValue;
|
|
19822
|
+
}
|
|
19823
|
+
/**
|
|
19824
|
+
* Gets default value for a JSON Schema type
|
|
19825
|
+
*/
|
|
19826
|
+
static getDefaultValueForType(type) {
|
|
19827
|
+
switch (type) {
|
|
19828
|
+
case 'string': return '';
|
|
19829
|
+
case 'number': return 0;
|
|
19830
|
+
case 'integer': return 0;
|
|
19831
|
+
case 'boolean': return false;
|
|
19832
|
+
case 'array': return [];
|
|
19833
|
+
case 'object': return {};
|
|
19834
|
+
default: return '';
|
|
19835
|
+
}
|
|
19836
|
+
}
|
|
18321
19837
|
}
|
|
18322
19838
|
_Ad4mModel_baseExpression = new WeakMap(), _Ad4mModel_subjectClassName = new WeakMap(), _Ad4mModel_source = new WeakMap(), _Ad4mModel_perspective = new WeakMap();
|
|
18323
19839
|
Ad4mModel.classNamesByClass = new WeakMap();
|
|
@@ -18345,6 +19861,7 @@ class ModelQueryBuilder {
|
|
|
18345
19861
|
constructor(perspective, ctor, query) {
|
|
18346
19862
|
this.queryParams = {};
|
|
18347
19863
|
this.modelClassName = null;
|
|
19864
|
+
this.useSurrealDBFlag = true;
|
|
18348
19865
|
this.perspective = perspective;
|
|
18349
19866
|
this.ctor = ctor;
|
|
18350
19867
|
if (query)
|
|
@@ -18482,6 +19999,35 @@ class ModelQueryBuilder {
|
|
|
18482
19999
|
this.modelClassName = className;
|
|
18483
20000
|
return this;
|
|
18484
20001
|
}
|
|
20002
|
+
/**
|
|
20003
|
+
* Enables or disables SurrealDB query path.
|
|
20004
|
+
*
|
|
20005
|
+
* @param enabled - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
|
|
20006
|
+
* @returns The query builder for chaining
|
|
20007
|
+
*
|
|
20008
|
+
* @example
|
|
20009
|
+
* ```typescript
|
|
20010
|
+
* // Use SurrealDB (default)
|
|
20011
|
+
* const recipes = await Recipe.query(perspective)
|
|
20012
|
+
* .where({ category: "Dessert" })
|
|
20013
|
+
* .useSurrealDB(true)
|
|
20014
|
+
* .get();
|
|
20015
|
+
*
|
|
20016
|
+
* // Use Prolog (legacy)
|
|
20017
|
+
* const recipesProlog = await Recipe.query(perspective)
|
|
20018
|
+
* .where({ category: "Dessert" })
|
|
20019
|
+
* .useSurrealDB(false)
|
|
20020
|
+
* .get();
|
|
20021
|
+
* ```
|
|
20022
|
+
*
|
|
20023
|
+
* @remarks
|
|
20024
|
+
* Note: Subscriptions (subscribe(), countSubscribe(), paginateSubscribe()) default to SurrealDB live queries
|
|
20025
|
+
* if useSurrealDB(true) is set (default).
|
|
20026
|
+
*/
|
|
20027
|
+
useSurrealDB(enabled = true) {
|
|
20028
|
+
this.useSurrealDBFlag = enabled;
|
|
20029
|
+
return this;
|
|
20030
|
+
}
|
|
18485
20031
|
/**
|
|
18486
20032
|
* Executes the query once and returns the results.
|
|
18487
20033
|
*
|
|
@@ -18495,16 +20041,24 @@ class ModelQueryBuilder {
|
|
|
18495
20041
|
* ```
|
|
18496
20042
|
*/
|
|
18497
20043
|
async get() {
|
|
18498
|
-
|
|
18499
|
-
|
|
18500
|
-
|
|
18501
|
-
|
|
20044
|
+
if (this.useSurrealDBFlag) {
|
|
20045
|
+
const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
|
|
20046
|
+
const result = await this.perspective.querySurrealDB(surrealQuery);
|
|
20047
|
+
const { results } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
|
|
20048
|
+
return results;
|
|
20049
|
+
}
|
|
20050
|
+
else {
|
|
20051
|
+
const query = await this.ctor.queryToProlog(this.perspective, this.queryParams, this.modelClassName);
|
|
20052
|
+
const result = await this.perspective.infer(query);
|
|
20053
|
+
const { results } = await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, result);
|
|
20054
|
+
return results;
|
|
20055
|
+
}
|
|
18502
20056
|
}
|
|
18503
20057
|
/**
|
|
18504
20058
|
* Subscribes to the query and receives updates when results change.
|
|
18505
20059
|
*
|
|
18506
20060
|
* This method:
|
|
18507
|
-
* 1. Creates and initializes a
|
|
20061
|
+
* 1. Creates and initializes a SurrealDB live query subscription (default)
|
|
18508
20062
|
* 2. Sets up the callback to process future updates
|
|
18509
20063
|
* 3. Returns the initial results immediately
|
|
18510
20064
|
*
|
|
@@ -18526,19 +20080,41 @@ class ModelQueryBuilder {
|
|
|
18526
20080
|
* // When done with subscription:
|
|
18527
20081
|
* builder.dispose();
|
|
18528
20082
|
* ```
|
|
20083
|
+
*
|
|
20084
|
+
* @remarks
|
|
20085
|
+
* By default, this uses SurrealDB live queries for real-time updates.
|
|
20086
|
+
* Prolog subscriptions remain available via `.useSurrealDB(false)`.
|
|
18529
20087
|
*/
|
|
18530
20088
|
async subscribe(callback) {
|
|
18531
20089
|
// Clean up any existing subscription
|
|
18532
20090
|
this.dispose();
|
|
18533
|
-
|
|
18534
|
-
|
|
18535
|
-
|
|
18536
|
-
const
|
|
18537
|
-
|
|
18538
|
-
|
|
18539
|
-
|
|
18540
|
-
|
|
18541
|
-
|
|
20091
|
+
if (this.useSurrealDBFlag) {
|
|
20092
|
+
const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
|
|
20093
|
+
this.currentSubscription = await this.perspective.subscribeSurrealDB(surrealQuery);
|
|
20094
|
+
const processResults = async (result) => {
|
|
20095
|
+
// The result from live query subscription update (handled in PerspectiveInstance listener)
|
|
20096
|
+
// is the new full set of results (because we re-query in Rust).
|
|
20097
|
+
// So we just need to map it to instances.
|
|
20098
|
+
const { results } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
|
|
20099
|
+
callback(results);
|
|
20100
|
+
};
|
|
20101
|
+
this.currentSubscription.onResult(processResults);
|
|
20102
|
+
// Process initial result
|
|
20103
|
+
const { results } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, this.currentSubscription.result);
|
|
20104
|
+
return results;
|
|
20105
|
+
}
|
|
20106
|
+
else {
|
|
20107
|
+
// Note: Subscriptions currently only work with Prolog
|
|
20108
|
+
const query = await this.ctor.queryToProlog(this.perspective, this.queryParams, this.modelClassName);
|
|
20109
|
+
this.currentSubscription = await this.perspective.subscribeInfer(query);
|
|
20110
|
+
const processResults = async (result) => {
|
|
20111
|
+
const { results } = await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, result);
|
|
20112
|
+
callback(results);
|
|
20113
|
+
};
|
|
20114
|
+
this.currentSubscription.onResult(processResults);
|
|
20115
|
+
const { results } = await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, this.currentSubscription.result);
|
|
20116
|
+
return results;
|
|
20117
|
+
}
|
|
18542
20118
|
}
|
|
18543
20119
|
/**
|
|
18544
20120
|
* Gets the total count of matching entities.
|
|
@@ -18553,15 +20129,26 @@ class ModelQueryBuilder {
|
|
|
18553
20129
|
* ```
|
|
18554
20130
|
*/
|
|
18555
20131
|
async count() {
|
|
18556
|
-
|
|
18557
|
-
|
|
18558
|
-
|
|
20132
|
+
if (this.useSurrealDBFlag) {
|
|
20133
|
+
const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
|
|
20134
|
+
const result = await this.perspective.querySurrealDB(surrealQuery);
|
|
20135
|
+
// Use instancesFromSurrealResult to apply JS-level filtering for advanced where conditions
|
|
20136
|
+
// (e.g., gt, gte, lt, lte, between, contains on properties and author/timestamp)
|
|
20137
|
+
// This ensures count() returns the same number as get().length
|
|
20138
|
+
const { totalCount } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
|
|
20139
|
+
return totalCount;
|
|
20140
|
+
}
|
|
20141
|
+
else {
|
|
20142
|
+
const query = await this.ctor.countQueryToProlog(this.perspective, this.queryParams, this.modelClassName);
|
|
20143
|
+
const result = await this.perspective.infer(query);
|
|
20144
|
+
return result?.[0]?.TotalCount || 0;
|
|
20145
|
+
}
|
|
18559
20146
|
}
|
|
18560
20147
|
/**
|
|
18561
20148
|
* Subscribes to count updates for matching entities.
|
|
18562
20149
|
*
|
|
18563
20150
|
* This method:
|
|
18564
|
-
* 1. Creates and initializes a
|
|
20151
|
+
* 1. Creates and initializes a SurrealDB live query subscription for the count (default)
|
|
18565
20152
|
* 2. Sets up the callback to process future count updates
|
|
18566
20153
|
* 3. Returns the initial count immediately
|
|
18567
20154
|
*
|
|
@@ -18583,18 +20170,35 @@ class ModelQueryBuilder {
|
|
|
18583
20170
|
* // When done with subscription:
|
|
18584
20171
|
* builder.dispose();
|
|
18585
20172
|
* ```
|
|
20173
|
+
*
|
|
20174
|
+
* @remarks
|
|
20175
|
+
* By default, this uses SurrealDB live queries for real-time updates.
|
|
20176
|
+
* Prolog subscriptions remain available via `.useSurrealDB(false)`.
|
|
18586
20177
|
*/
|
|
18587
20178
|
async countSubscribe(callback) {
|
|
18588
20179
|
// Clean up any existing subscription
|
|
18589
20180
|
this.dispose();
|
|
18590
|
-
|
|
18591
|
-
|
|
18592
|
-
|
|
18593
|
-
const
|
|
18594
|
-
|
|
18595
|
-
|
|
18596
|
-
|
|
18597
|
-
|
|
20181
|
+
if (this.useSurrealDBFlag) {
|
|
20182
|
+
const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
|
|
20183
|
+
this.currentSubscription = await this.perspective.subscribeSurrealDB(surrealQuery);
|
|
20184
|
+
const processResults = async (result) => {
|
|
20185
|
+
const { totalCount } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
|
|
20186
|
+
callback(totalCount);
|
|
20187
|
+
};
|
|
20188
|
+
this.currentSubscription.onResult(processResults);
|
|
20189
|
+
const { totalCount } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, this.currentSubscription.result);
|
|
20190
|
+
return totalCount;
|
|
20191
|
+
}
|
|
20192
|
+
else {
|
|
20193
|
+
const query = await this.ctor.countQueryToProlog(this.perspective, this.queryParams, this.modelClassName);
|
|
20194
|
+
this.currentSubscription = await this.perspective.subscribeInfer(query);
|
|
20195
|
+
const processResults = async (result) => {
|
|
20196
|
+
const newCount = result?.[0]?.TotalCount || 0;
|
|
20197
|
+
callback(newCount);
|
|
20198
|
+
};
|
|
20199
|
+
this.currentSubscription.onResult(processResults);
|
|
20200
|
+
return this.currentSubscription.result?.[0]?.TotalCount || 0;
|
|
20201
|
+
}
|
|
18598
20202
|
}
|
|
18599
20203
|
/**
|
|
18600
20204
|
* Gets a page of results with pagination metadata.
|
|
@@ -18613,16 +20217,24 @@ class ModelQueryBuilder {
|
|
|
18613
20217
|
*/
|
|
18614
20218
|
async paginate(pageSize, pageNumber) {
|
|
18615
20219
|
const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
|
|
18616
|
-
|
|
18617
|
-
|
|
18618
|
-
|
|
18619
|
-
|
|
20220
|
+
if (this.useSurrealDBFlag) {
|
|
20221
|
+
const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, paginationQuery);
|
|
20222
|
+
const result = await this.perspective.querySurrealDB(surrealQuery);
|
|
20223
|
+
const { results, totalCount } = (await this.ctor.instancesFromSurrealResult(this.perspective, paginationQuery, result));
|
|
20224
|
+
return { results, totalCount, pageSize, pageNumber };
|
|
20225
|
+
}
|
|
20226
|
+
else {
|
|
20227
|
+
const prologQuery = await this.ctor.queryToProlog(this.perspective, paginationQuery, this.modelClassName);
|
|
20228
|
+
const result = await this.perspective.infer(prologQuery);
|
|
20229
|
+
const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, paginationQuery, result));
|
|
20230
|
+
return { results, totalCount, pageSize, pageNumber };
|
|
20231
|
+
}
|
|
18620
20232
|
}
|
|
18621
20233
|
/**
|
|
18622
20234
|
* Subscribes to paginated results updates.
|
|
18623
20235
|
*
|
|
18624
20236
|
* This method:
|
|
18625
|
-
* 1. Creates and initializes a
|
|
20237
|
+
* 1. Creates and initializes a SurrealDB live query subscription for the paginated results (default)
|
|
18626
20238
|
* 2. Sets up the callback to process future page updates
|
|
18627
20239
|
* 3. Returns the initial page immediately
|
|
18628
20240
|
*
|
|
@@ -18646,20 +20258,37 @@ class ModelQueryBuilder {
|
|
|
18646
20258
|
* // When done with subscription:
|
|
18647
20259
|
* builder.dispose();
|
|
18648
20260
|
* ```
|
|
20261
|
+
*
|
|
20262
|
+
* @remarks
|
|
20263
|
+
* By default, this uses SurrealDB live queries for real-time updates.
|
|
20264
|
+
* Prolog subscriptions remain available via `.useSurrealDB(false)`.
|
|
18649
20265
|
*/
|
|
18650
20266
|
async paginateSubscribe(pageSize, pageNumber, callback) {
|
|
18651
20267
|
// Clean up any existing subscription
|
|
18652
20268
|
this.dispose();
|
|
18653
20269
|
const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
|
|
18654
|
-
|
|
18655
|
-
|
|
18656
|
-
|
|
18657
|
-
const
|
|
18658
|
-
|
|
18659
|
-
|
|
18660
|
-
|
|
18661
|
-
|
|
18662
|
-
|
|
20270
|
+
if (this.useSurrealDBFlag) {
|
|
20271
|
+
const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, paginationQuery);
|
|
20272
|
+
this.currentSubscription = await this.perspective.subscribeSurrealDB(surrealQuery);
|
|
20273
|
+
const processResults = async (result) => {
|
|
20274
|
+
const { results, totalCount } = (await this.ctor.instancesFromSurrealResult(this.perspective, paginationQuery, result));
|
|
20275
|
+
callback({ results, totalCount, pageSize, pageNumber });
|
|
20276
|
+
};
|
|
20277
|
+
this.currentSubscription.onResult(processResults);
|
|
20278
|
+
const { results, totalCount } = (await this.ctor.instancesFromSurrealResult(this.perspective, paginationQuery, this.currentSubscription.result));
|
|
20279
|
+
return { results, totalCount, pageSize, pageNumber };
|
|
20280
|
+
}
|
|
20281
|
+
else {
|
|
20282
|
+
const prologQuery = await this.ctor.queryToProlog(this.perspective, paginationQuery, this.modelClassName);
|
|
20283
|
+
this.currentSubscription = await this.perspective.subscribeInfer(prologQuery);
|
|
20284
|
+
const processResults = async (r) => {
|
|
20285
|
+
const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, r));
|
|
20286
|
+
callback({ results, totalCount, pageSize, pageNumber });
|
|
20287
|
+
};
|
|
20288
|
+
this.currentSubscription.onResult(processResults);
|
|
20289
|
+
const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, paginationQuery, this.currentSubscription.result));
|
|
20290
|
+
return { results, totalCount, pageSize, pageNumber };
|
|
20291
|
+
}
|
|
18663
20292
|
}
|
|
18664
20293
|
}
|
|
18665
20294
|
|