/
realm_core.dart
3891 lines (3307 loc) · 148 KB
/
realm_core.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2021 MongoDB, Inc.
// SPDX-License-Identifier: Apache-2.0
// ignore_for_file: non_constant_identifier_names
import 'dart:async';
import 'dart:convert';
import 'dart:ffi';
import 'dart:io';
import 'dart:isolate';
import 'dart:typed_data';
import 'package:cancellation_token/cancellation_token.dart';
import 'package:crypto/crypto.dart';
// Hide StringUtf8Pointer.toNativeUtf8 and StringUtf16Pointer since these allows silently allocating memory. Use toUtf8Ptr instead
import 'package:ffi/ffi.dart' hide StringUtf8Pointer, StringUtf16Pointer;
import 'package:path/path.dart' as path;
import 'package:pubspec_parse/pubspec_parse.dart';
import 'package:realm_common/realm_common.dart' as common show Decimal128;
import 'package:realm_common/realm_common.dart' hide Decimal128;
import 'package:realm_dart/src/logging.dart';
import '../app.dart';
import '../collections.dart';
import '../configuration.dart';
import '../credentials.dart';
import '../init.dart';
import '../list.dart';
import '../map.dart';
import '../migration.dart';
import '../realm_class.dart';
import '../realm_object.dart';
import '../results.dart';
import '../scheduler.dart';
import '../session.dart';
import '../set.dart';
import '../subscription.dart';
import '../user.dart';
import 'realm_bindings.dart';
part 'decimal128.dart';
const bugInTheSdkMessage = "This is likely a bug in the Realm SDK - please file an issue at https://github.com/realm/realm-dart/issues";
// This variable allows access to realm native library even before RealmCore is created. For Decimal128 for example
final _realmLib = () {
final result = RealmLibrary(initRealm());
final nativeLibraryVersion = result.realm_dart_library_version().cast<Utf8>().toDartString();
if (libraryVersion != nativeLibraryVersion) {
final additionMessage =
isFlutterPlatform ? bugInTheSdkMessage : "Did you forget to run `dart run realm_dart install` after upgrading the realm_dart package?";
throw RealmException('Realm SDK package version does not match the native library version ($libraryVersion != $nativeLibraryVersion). $additionMessage');
}
return result;
}();
final _pluginLib = () {
if (!isFlutterPlatform) {
throw UnsupportedError("Realm plugin library used outside Flutter");
}
if (Platform.isIOS) {
return DynamicLibrary.executable();
}
String plugin = Platform.isWindows
? 'realm_plugin.dll'
: Platform.isMacOS
? 'realm.framework/realm' // use catalyst
: Platform.isLinux
? "librealm_plugin.so"
: throw UnsupportedError("Platform ${Platform.operatingSystem} is not supported");
final pluginLib = DynamicLibrary.open(plugin);
return pluginLib;
}();
// stamped into the library by the build system (see prepare-release.yml)
const libraryVersion = '2.0.0-beta.1';
_RealmCore realmCore = _RealmCore();
// All access to Realm Core functionality goes through this class
class _RealmCore {
// From realm.h. Currently not exported from the shared library
// ignore: unused_field, constant_identifier_names
static const int RLM_INVALID_CLASS_KEY = 0x7FFFFFFF;
// ignore: unused_field, constant_identifier_names
static const int RLM_INVALID_PROPERTY_KEY = -1;
// ignore: unused_field, constant_identifier_names
static const int RLM_INVALID_OBJECT_KEY = -1;
final encryptionKeySize = 64;
// ignore: unused_field
static late final _RealmCore _instance;
_RealmCore() {
// This disables creation of a second _RealmCore instance effectivelly making `realmCore` global variable readonly
_instance = this;
// This prevents reentrance if `realmCore` global variable is accessed during _RealmCore construction
realmCore = this;
_realmLib.realm_dart_init_debug_logger();
}
void loggerAttach() {
_realmLib.realm_dart_attach_logger(scheduler.nativePort);
}
void loggerDetach() {
_realmLib.realm_dart_detach_logger(scheduler.nativePort);
}
// for debugging only. Enable in realm_dart.cpp
// void invokeGC() {
// _realmLib.realm_dart_gc();
// }
LastError? getLastError(Allocator allocator) {
final error = allocator<realm_error_t>();
final success = _realmLib.realm_get_last_error(error);
if (!success) {
return null;
}
return error.ref.toLastError();
}
void throwLastError([String? errorMessage]) {
using((Arena arena) {
final lastError = getLastError(arena);
if (lastError?.userError != null) {
throw UserCallbackException(lastError!.userError!);
}
final message = '${errorMessage != null ? "$errorMessage. " : ""}${lastError ?? ""}';
switch (lastError?.code) {
case realm_errno.RLM_ERR_SCHEMA_MISMATCH:
throw MigrationRequiredException(message);
default:
throw RealmException(message);
}
});
}
SchemaHandle _createSchema(Iterable<SchemaObject> schema) {
return using((Arena arena) {
final classCount = schema.length;
final schemaClasses = arena<realm_class_info_t>(classCount);
final schemaProperties = arena<Pointer<realm_property_info_t>>(classCount);
for (var i = 0; i < classCount; i++) {
final schemaObject = schema.elementAt(i);
final classInfo = schemaClasses.elementAt(i).ref;
final propertiesCount = schemaObject.length;
final computedCount = schemaObject.where((p) => p.isComputed).length;
final persistedCount = propertiesCount - computedCount;
classInfo.name = schemaObject.name.toCharPtr(arena);
classInfo.primary_key = "".toCharPtr(arena);
classInfo.num_properties = persistedCount;
classInfo.num_computed_properties = computedCount;
classInfo.key = RLM_INVALID_CLASS_KEY;
classInfo.flags = schemaObject.baseType.flags;
final properties = arena<realm_property_info_t>(propertiesCount);
for (var j = 0; j < propertiesCount; j++) {
final schemaProperty = schemaObject[j];
final propInfo = properties.elementAt(j).ref;
propInfo.name = schemaProperty.mapTo.toCharPtr(arena);
propInfo.public_name = (schemaProperty.mapTo != schemaProperty.name ? schemaProperty.name : '').toCharPtr(arena);
propInfo.link_target = (schemaProperty.linkTarget ?? "").toCharPtr(arena);
propInfo.link_origin_property_name = (schemaProperty.linkOriginProperty ?? "").toCharPtr(arena);
propInfo.type = schemaProperty.propertyType.index;
propInfo.collection_type = schemaProperty.collectionType.index;
propInfo.flags = realm_property_flags.RLM_PROPERTY_NORMAL;
if (schemaProperty.optional) {
propInfo.flags |= realm_property_flags.RLM_PROPERTY_NULLABLE;
}
switch (schemaProperty.indexType) {
case RealmIndexType.regular:
propInfo.flags |= realm_property_flags.RLM_PROPERTY_INDEXED;
break;
case RealmIndexType.fullText:
propInfo.flags |= realm_property_flags.RLM_PROPERTY_FULLTEXT_INDEXED;
break;
default:
break;
}
if (schemaProperty.primaryKey) {
classInfo.primary_key = schemaProperty.mapTo.toCharPtr(arena);
propInfo.flags |= realm_property_flags.RLM_PROPERTY_PRIMARY_KEY;
}
}
schemaProperties[i] = properties;
schemaProperties.elementAt(i).value = properties;
}
final schemaPtr = _realmLib.invokeGetPointer(() => _realmLib.realm_schema_new(schemaClasses, classCount, schemaProperties));
return SchemaHandle._(schemaPtr);
});
}
ConfigHandle _createConfig(Configuration config) {
return using((Arena arena) {
final configPtr = _realmLib.realm_config_new();
final configHandle = ConfigHandle._(configPtr);
if (config.schemaObjects.isNotEmpty) {
final schemaHandle = _createSchema(config.schemaObjects);
_realmLib.realm_config_set_schema(configHandle._pointer, schemaHandle._pointer);
}
_realmLib.realm_config_set_path(configHandle._pointer, config.path.toCharPtr(arena));
_realmLib.realm_config_set_scheduler(configHandle._pointer, scheduler.handle._pointer);
if (config.fifoFilesFallbackPath != null) {
_realmLib.realm_config_set_fifo_path(configHandle._pointer, config.fifoFilesFallbackPath!.toCharPtr(arena));
}
// Setting schema version only makes sense for local realms, but core insists it is always set,
// hence we set it to 0 in those cases.
_realmLib.realm_config_set_schema_version(configHandle._pointer, config is LocalConfiguration ? config.schemaVersion : 0);
if (config.maxNumberOfActiveVersions != null) {
_realmLib.realm_config_set_max_number_of_active_versions(configHandle._pointer, config.maxNumberOfActiveVersions!);
}
if (config is LocalConfiguration) {
//_realmLib.realm_config_set_schema_mode(configHandle._pointer, realm_schema_mode.RLM_SCHEMA_MODE_ADDITIVE_DISCOVERED);
if (config.initialDataCallback != null) {
_realmLib.realm_config_set_data_initialization_function(
configHandle._pointer,
Pointer.fromFunction(initial_data_callback, false),
config.toPersistentHandle(),
_realmLib.addresses.realm_dart_delete_persistent_handle,
);
}
if (config.isReadOnly) {
_realmLib.realm_config_set_schema_mode(configHandle._pointer, realm_schema_mode.RLM_SCHEMA_MODE_IMMUTABLE);
} else if (config.shouldDeleteIfMigrationNeeded) {
_realmLib.realm_config_set_schema_mode(configHandle._pointer, realm_schema_mode.RLM_SCHEMA_MODE_SOFT_RESET_FILE);
}
if (config.disableFormatUpgrade) {
_realmLib.realm_config_set_disable_format_upgrade(configHandle._pointer, config.disableFormatUpgrade);
}
if (config.shouldCompactCallback != null) {
_realmLib.realm_config_set_should_compact_on_launch_function(
configHandle._pointer,
Pointer.fromFunction(should_compact_callback, false),
config.toPersistentHandle(),
_realmLib.addresses.realm_dart_delete_persistent_handle,
);
}
if (config.migrationCallback != null) {
_realmLib.realm_config_set_migration_function(
configHandle._pointer,
Pointer.fromFunction(migration_callback, false),
config.toPersistentHandle(),
_realmLib.addresses.realm_dart_delete_persistent_handle,
);
}
} else if (config is InMemoryConfiguration) {
_realmLib.realm_config_set_in_memory(configHandle._pointer, true);
} else if (config is FlexibleSyncConfiguration) {
_realmLib.realm_config_set_schema_mode(configHandle._pointer, realm_schema_mode.RLM_SCHEMA_MODE_ADDITIVE_DISCOVERED);
final syncConfigPtr = _realmLib.invokeGetPointer(() => _realmLib.realm_flx_sync_config_new(config.user.handle._pointer));
try {
_realmLib.realm_sync_config_set_session_stop_policy(syncConfigPtr, config.sessionStopPolicy.index);
_realmLib.realm_sync_config_set_resync_mode(syncConfigPtr, config.clientResetHandler.clientResyncMode.index);
final errorHandlerCallback =
Pointer.fromFunction<Void Function(Handle, Pointer<realm_sync_session_t>, realm_sync_error_t)>(_syncErrorHandlerCallback);
final errorHandlerUserdata = _realmLib.realm_dart_userdata_async_new(config, errorHandlerCallback.cast(), scheduler.handle._pointer);
_realmLib.realm_sync_config_set_error_handler(syncConfigPtr, _realmLib.addresses.realm_dart_sync_error_handler_callback, errorHandlerUserdata.cast(),
_realmLib.addresses.realm_dart_userdata_async_free);
if (config.clientResetHandler.onBeforeReset != null) {
final syncBeforeResetCallback = Pointer.fromFunction<Void Function(Handle, Pointer<shared_realm>, Pointer<Void>)>(_syncBeforeResetCallback);
final beforeResetUserdata = _realmLib.realm_dart_userdata_async_new(config, syncBeforeResetCallback.cast(), scheduler.handle._pointer);
_realmLib.realm_sync_config_set_before_client_reset_handler(syncConfigPtr, _realmLib.addresses.realm_dart_sync_before_reset_handler_callback,
beforeResetUserdata.cast(), _realmLib.addresses.realm_dart_userdata_async_free);
}
if (config.clientResetHandler.onAfterRecovery != null || config.clientResetHandler.onAfterDiscard != null) {
final syncAfterResetCallback =
Pointer.fromFunction<Void Function(Handle, Pointer<shared_realm>, Pointer<realm_thread_safe_reference>, Bool, Pointer<Void>)>(
_syncAfterResetCallback);
final afterResetUserdata = _realmLib.realm_dart_userdata_async_new(config, syncAfterResetCallback.cast(), scheduler.handle._pointer);
_realmLib.realm_sync_config_set_after_client_reset_handler(syncConfigPtr, _realmLib.addresses.realm_dart_sync_after_reset_handler_callback,
afterResetUserdata.cast(), _realmLib.addresses.realm_dart_userdata_async_free);
}
if (config.shouldCompactCallback != null) {
_realmLib.realm_config_set_should_compact_on_launch_function(
configHandle._pointer,
Pointer.fromFunction(should_compact_callback, false),
config.toPersistentHandle(),
_realmLib.addresses.realm_dart_delete_persistent_handle,
);
}
_realmLib.realm_config_set_sync_config(configPtr, syncConfigPtr);
} finally {
_realmLib.realm_release(syncConfigPtr.cast());
}
} else if (config is DisconnectedSyncConfiguration) {
_realmLib.realm_config_set_schema_mode(configHandle._pointer, realm_schema_mode.RLM_SCHEMA_MODE_ADDITIVE_EXPLICIT);
_realmLib.realm_config_set_force_sync_history(configPtr, true);
}
if (config.encryptionKey != null) {
_realmLib.realm_config_set_encryption_key(configPtr, config.encryptionKey!.toUint8Ptr(arena), encryptionKeySize);
}
// For sync and for dynamic Realms, we need to have a complete view of the schema in Core.
if (config.schemaObjects.isEmpty || config is FlexibleSyncConfiguration) {
_realmLib.realm_config_set_schema_subset_mode(configHandle._pointer, realm_schema_subset_mode.RLM_SCHEMA_SUBSET_MODE_COMPLETE);
}
return configHandle;
});
}
String getPathForUser(User user) {
final syncConfigPtr = _realmLib.invokeGetPointer(() => _realmLib.realm_flx_sync_config_new(user.handle._pointer));
try {
final path = _realmLib.realm_app_sync_client_get_default_file_path_for_realm(syncConfigPtr, nullptr);
return path.cast<Utf8>().toRealmDartString(freeRealmMemory: true)!;
} finally {
_realmLib.realm_release(syncConfigPtr.cast());
}
}
ObjectId subscriptionId(Subscription subscription) {
final id = _realmLib.realm_sync_subscription_id(subscription.handle._pointer);
return id.toDart();
}
String? subscriptionName(Subscription subscription) {
final name = _realmLib.realm_sync_subscription_name(subscription.handle._pointer);
return name.toDart();
}
String subscriptionObjectClassName(Subscription subscription) {
final objectClassName = _realmLib.realm_sync_subscription_object_class_name(subscription.handle._pointer);
return objectClassName.toDart()!;
}
String subscriptionQueryString(Subscription subscription) {
final queryString = _realmLib.realm_sync_subscription_query_string(subscription.handle._pointer);
return queryString.toDart()!;
}
DateTime subscriptionCreatedAt(Subscription subscription) {
final createdAt = _realmLib.realm_sync_subscription_created_at(subscription.handle._pointer);
return createdAt.toDart();
}
DateTime subscriptionUpdatedAt(Subscription subscription) {
final updatedAt = _realmLib.realm_sync_subscription_updated_at(subscription.handle._pointer);
return updatedAt.toDart();
}
SubscriptionSetHandle getSubscriptions(Realm realm) {
return SubscriptionSetHandle._(_realmLib.invokeGetPointer(() => _realmLib.realm_sync_get_active_subscription_set(realm.handle._pointer)), realm.handle);
}
void refreshSubscriptions(SubscriptionSet subscriptions) {
_realmLib.invokeGetBool(() => _realmLib.realm_sync_subscription_set_refresh(subscriptions.handle._pointer));
}
int getSubscriptionSetSize(SubscriptionSet subscriptions) {
return _realmLib.realm_sync_subscription_set_size(subscriptions.handle._pointer);
}
Exception? getSubscriptionSetError(SubscriptionSet subscriptions) {
final error = _realmLib.realm_sync_subscription_set_error_str(subscriptions.handle._pointer);
final message = error.cast<Utf8>().toRealmDartString(treatEmptyAsNull: true);
return message == null ? null : RealmException(message);
}
SubscriptionHandle subscriptionAt(SubscriptionSet subscriptions, int index) {
return SubscriptionHandle._(_realmLib.invokeGetPointer(() => _realmLib.realm_sync_subscription_at(
subscriptions.handle._pointer,
index,
)));
}
SubscriptionHandle? findSubscriptionByName(SubscriptionSet subscriptions, String name) {
return using((arena) {
final result = _realmLib.realm_sync_find_subscription_by_name(
subscriptions.handle._pointer,
name.toCharPtr(arena),
);
return result == nullptr ? null : SubscriptionHandle._(result);
});
}
SubscriptionHandle? findSubscriptionByResults(SubscriptionSet subscriptions, RealmResults results) {
final result = _realmLib.realm_sync_find_subscription_by_results(
subscriptions.handle._pointer,
results.handle._pointer,
);
return result == nullptr ? null : SubscriptionHandle._(result);
}
static void _stateChangeCallback(Object userdata, int state) {
final completer = userdata as CancellableCompleter<SubscriptionSetState>;
if (!completer.isCancelled) {
completer.complete(SubscriptionSetState.values[state]);
}
}
Future<SubscriptionSetState> waitForSubscriptionSetStateChange(SubscriptionSet subscriptions, SubscriptionSetState notifyWhen,
[CancellationToken? cancellationToken]) {
final completer = CancellableCompleter<SubscriptionSetState>(cancellationToken);
if (!completer.isCancelled) {
final callback = Pointer.fromFunction<Void Function(Handle, Int32)>(_stateChangeCallback);
final userdata = _realmLib.realm_dart_userdata_async_new(completer, callback.cast(), scheduler.handle._pointer);
_realmLib.realm_sync_on_subscription_set_state_change_async(subscriptions.handle._pointer, notifyWhen.index,
_realmLib.addresses.realm_dart_sync_on_subscription_state_changed_callback, userdata.cast(), _realmLib.addresses.realm_dart_userdata_async_free);
}
return completer.future;
}
int subscriptionSetGetVersion(SubscriptionSet subscriptions) {
return _realmLib.realm_sync_subscription_set_version(subscriptions.handle._pointer);
}
SubscriptionSetState subscriptionSetGetState(SubscriptionSet subscriptions) {
return SubscriptionSetState.values[_realmLib.realm_sync_subscription_set_state(subscriptions.handle._pointer)];
}
MutableSubscriptionSetHandle subscriptionSetMakeMutable(SubscriptionSet subscriptions) {
return MutableSubscriptionSetHandle._(
_realmLib.invokeGetPointer(() => _realmLib.realm_sync_make_subscription_set_mutable(subscriptions.handle._pointer)), subscriptions.realm.handle);
}
SubscriptionSetHandle subscriptionSetCommit(MutableSubscriptionSet subscriptions) {
return SubscriptionSetHandle._(
_realmLib.invokeGetPointer(() => _realmLib.realm_sync_subscription_set_commit(subscriptions.handle._mutablePointer)), subscriptions.realm.handle);
}
SubscriptionHandle insertOrAssignSubscription(MutableSubscriptionSet subscriptions, RealmResults results, String? name, bool update) {
if (!update) {
if (name != null && findSubscriptionByName(subscriptions, name) != null) {
throw RealmException('Duplicate subscription with name: $name');
}
}
return using((arena) {
final out_index = arena<Size>();
final out_inserted = arena<Bool>();
_realmLib.invokeGetBool(() => _realmLib.realm_sync_subscription_set_insert_or_assign_results(
subscriptions.handle._mutablePointer,
results.handle._pointer,
name?.toCharPtr(arena) ?? nullptr,
out_index,
out_inserted,
));
return subscriptionAt(subscriptions, out_index.value);
});
}
bool eraseSubscriptionById(MutableSubscriptionSet subscriptions, Subscription subscription) {
return using((arena) {
final out_found = arena<Bool>();
_realmLib.invokeGetBool(() => _realmLib.realm_sync_subscription_set_erase_by_id(
subscriptions.handle._mutablePointer,
subscription.id.toNative(arena),
out_found,
));
return out_found.value;
});
}
bool eraseSubscriptionByName(MutableSubscriptionSet subscriptions, String name) {
return using((arena) {
final out_found = arena<Bool>();
_realmLib.invokeGetBool(() => _realmLib.realm_sync_subscription_set_erase_by_name(
subscriptions.handle._mutablePointer,
name.toCharPtr(arena),
out_found,
));
return out_found.value;
});
}
bool eraseSubscriptionByResults(MutableSubscriptionSet subscriptions, RealmResults results) {
return using((arena) {
final out_found = arena<Bool>();
_realmLib.invokeGetBool(() => _realmLib.realm_sync_subscription_set_erase_by_results(
subscriptions.handle._mutablePointer,
results.handle._pointer,
out_found,
));
return out_found.value;
});
}
void clearSubscriptionSet(MutableSubscriptionSet subscriptions) {
_realmLib.invokeGetBool(() => _realmLib.realm_sync_subscription_set_clear(subscriptions.handle._mutablePointer));
}
void refreshSubscriptionSet(SubscriptionSet subscriptions) {
_realmLib.invokeGetBool(() => _realmLib.realm_sync_subscription_set_refresh(subscriptions.handle._pointer));
}
static bool initial_data_callback(Pointer<Void> userdata, Pointer<shared_realm> realmPtr) {
final realmHandle = RealmHandle._unowned(realmPtr);
try {
final LocalConfiguration config = userdata.toObject();
final realm = RealmInternal.getUnowned(config, realmHandle);
config.initialDataCallback!(realm);
return true;
} catch (ex) {
_realmLib.realm_register_user_code_callback_error(ex.toPersistentHandle());
} finally {
realmHandle.release();
}
return false;
}
static bool should_compact_callback(Pointer<Void> userdata, int totalSize, int usedSize) {
final config = userdata.toObject();
if (config is LocalConfiguration) {
return config.shouldCompactCallback!(totalSize, usedSize);
} else if (config is FlexibleSyncConfiguration) {
return config.shouldCompactCallback!(totalSize, usedSize);
}
return false;
}
static bool migration_callback(
Pointer<Void> userdata, Pointer<shared_realm> oldRealmHandle, Pointer<shared_realm> newRealmHandle, Pointer<realm_schema> schema) {
final oldHandle = RealmHandle._unowned(oldRealmHandle);
final newHandle = RealmHandle._unowned(newRealmHandle);
try {
final LocalConfiguration config = userdata.toObject();
final oldSchemaVersion = _realmLib.realm_get_schema_version(oldRealmHandle);
final oldConfig = Configuration.local([], path: config.path, isReadOnly: true, schemaVersion: oldSchemaVersion);
final oldRealm = RealmInternal.getUnowned(oldConfig, oldHandle, isInMigration: true);
final newRealm = RealmInternal.getUnowned(config, newHandle, isInMigration: true);
final migration = MigrationInternal.create(RealmInternal.getMigrationRealm(oldRealm), newRealm, SchemaHandle.unowned(schema));
config.migrationCallback!(migration, oldSchemaVersion);
return true;
} catch (ex) {
_realmLib.realm_register_user_code_callback_error(ex.toPersistentHandle());
} finally {
oldHandle.release();
newHandle.release();
}
return false;
}
static void _syncErrorHandlerCallback(Object userdata, Pointer<realm_sync_session> session, realm_sync_error error) {
final syncConfig = userdata as FlexibleSyncConfiguration;
// TODO: Take the app from the session instead of from syncConfig after fixing issue https://github.com/realm/realm-dart/issues/633
final syncError = SyncErrorInternal.createSyncError(error.toSyncErrorDetails(), app: syncConfig.user.app);
if (syncError is ClientResetError) {
syncConfig.clientResetHandler.onManualReset?.call(syncError);
return;
}
syncConfig.syncErrorHandler(syncError);
}
static void _guardSynchronousCallback(FutureOr<void> Function() callback, Pointer<Void> unlockCallbackFunc) async {
Pointer<Void> user_error = nullptr;
try {
await callback();
} catch (error) {
user_error = error.toPersistentHandle();
} finally {
_realmLib.realm_dart_invoke_unlock_callback(user_error, unlockCallbackFunc);
}
}
static void _syncBeforeResetCallback(Object userdata, Pointer<shared_realm> realmHandle, Pointer<Void> unlockCallbackFunc) {
_guardSynchronousCallback(() async {
final syncConfig = userdata as FlexibleSyncConfiguration;
var beforeResetCallback = syncConfig.clientResetHandler.onBeforeReset!;
final realm = RealmInternal.getUnowned(syncConfig, RealmHandle._unowned(realmHandle));
try {
await beforeResetCallback(realm);
} finally {
realm.handle.release();
}
}, unlockCallbackFunc);
}
static void _syncAfterResetCallback(Object userdata, Pointer<shared_realm> beforeHandle, Pointer<realm_thread_safe_reference> afterReference, bool didRecover,
Pointer<Void> unlockCallbackFunc) {
_guardSynchronousCallback(() async {
final syncConfig = userdata as FlexibleSyncConfiguration;
final afterResetCallback = didRecover ? syncConfig.clientResetHandler.onAfterRecovery : syncConfig.clientResetHandler.onAfterDiscard;
if (afterResetCallback == null) {
return;
}
final beforeRealm = RealmInternal.getUnowned(syncConfig, RealmHandle._unowned(beforeHandle));
final realmPtr = _realmLib.invokeGetPointer(() => _realmLib.realm_from_thread_safe_reference(afterReference, scheduler.handle._pointer));
final afterRealm = RealmInternal.getUnowned(syncConfig, RealmHandle._unowned(realmPtr));
try {
return await afterResetCallback(beforeRealm, afterRealm);
} finally {
beforeRealm.handle.release();
afterRealm.handle.release();
}
}, unlockCallbackFunc);
}
void raiseError(Session session, int errorCode, bool isFatal) {
using((arena) {
final message = "Simulated session error".toCharPtr(arena);
_realmLib.realm_sync_session_handle_error_for_testing(session.handle._pointer, errorCode, message, isFatal);
});
}
void realmDisableAutoRefreshForTesting(Realm realm) {
_realmLib.realm_set_auto_refresh(realm.handle._pointer, false);
}
SchedulerHandle createScheduler(int isolateId, int sendPort) {
final schedulerPtr = _realmLib.realm_dart_create_scheduler(isolateId, sendPort);
return SchedulerHandle._(schedulerPtr);
}
void invokeScheduler(int workQueue) {
final queuePointer = Pointer<realm_work_queue>.fromAddress(workQueue);
_realmLib.realm_scheduler_perform_work(queuePointer);
}
RealmHandle openRealm(Configuration config) {
final configHandle = _createConfig(config);
final realmPtr = _realmLib.invokeGetPointer(() => _realmLib.realm_open(configHandle._pointer), "Error opening realm at path ${config.path}");
return RealmHandle._(realmPtr);
}
RealmAsyncOpenTaskHandle createRealmAsyncOpenTask(FlexibleSyncConfiguration config) {
final configHandle = _createConfig(config);
final asyncOpenTaskPtr =
_realmLib.invokeGetPointer(() => _realmLib.realm_open_synchronized(configHandle._pointer), "Error opening realm at path ${config.path}");
return RealmAsyncOpenTaskHandle._(asyncOpenTaskPtr);
}
Future<RealmHandle> openRealmAsync(RealmAsyncOpenTaskHandle handle, CancellationToken? cancellationToken) {
final completer = CancellableCompleter<RealmHandle>(cancellationToken);
if (!completer.isCancelled) {
final callback =
Pointer.fromFunction<Void Function(Handle, Pointer<realm_thread_safe_reference> realm, Pointer<realm_async_error_t> error)>(_openRealmAsyncCallback);
final userData = _realmLib.realm_dart_userdata_async_new(completer, callback.cast(), scheduler.handle._pointer);
_realmLib.realm_async_open_task_start(
handle._pointer,
_realmLib.addresses.realm_dart_async_open_task_callback,
userData.cast(),
_realmLib.addresses.realm_dart_userdata_async_free,
);
}
return completer.future;
}
static void _openRealmAsyncCallback(Object userData, Pointer<realm_thread_safe_reference> realmSafePtr, Pointer<realm_async_error_t> error) {
return using((Arena arena) {
final completer = userData as CancellableCompleter<RealmHandle>;
if (completer.isCancelled) {
return;
}
if (error != nullptr) {
final err = arena<realm_error>();
bool success = _realmLib.realm_get_async_error(error, err);
final lastError = success ? err.ref.toLastError() : null;
completer.completeError(RealmException("Failed to open realm${lastError?.message ?? ''}"));
return;
}
final realmPtr = _realmLib.invokeGetPointer(() => _realmLib.realm_from_thread_safe_reference(realmSafePtr, scheduler.handle._pointer));
completer.complete(RealmHandle._(realmPtr));
});
}
void cancelOpenRealmAsync(RealmAsyncOpenTaskHandle handle) {
_realmLib.realm_async_open_task_cancel(handle._pointer);
}
RealmAsyncOpenTaskProgressNotificationTokenHandle realmAsyncOpenRegisterAsyncOpenProgressNotifier(
RealmAsyncOpenTaskHandle handle, RealmAsyncOpenProgressNotificationsController controller) {
final callback = Pointer.fromFunction<Void Function(Handle, Uint64, Uint64)>(_syncProgressCallback);
final userdata = _realmLib.realm_dart_userdata_async_new(controller, callback.cast(), scheduler.handle._pointer);
final tokenPtr = _realmLib.invokeGetPointer(() => _realmLib.realm_async_open_task_register_download_progress_notifier(
handle._pointer,
_realmLib.addresses.realm_dart_sync_progress_callback,
userdata.cast(),
_realmLib.addresses.realm_dart_userdata_async_free,
));
return RealmAsyncOpenTaskProgressNotificationTokenHandle._(tokenPtr);
}
RealmSchema readSchema(Realm realm) {
return using((Arena arena) {
return _readSchema(realm, arena);
});
}
RealmSchema _readSchema(Realm realm, Arena arena, {int expectedSize = 10}) {
final classesPtr = arena<Uint32>(expectedSize);
final actualCount = arena<Size>();
_realmLib.invokeGetBool(() => _realmLib.realm_get_class_keys(realm.handle._pointer, classesPtr, expectedSize, actualCount));
if (expectedSize < actualCount.value) {
arena.free(classesPtr);
return _readSchema(realm, arena, expectedSize: actualCount.value);
}
final schemas = <SchemaObject>[];
for (var i = 0; i < actualCount.value; i++) {
final classInfo = arena<realm_class_info>();
final classKey = classesPtr.elementAt(i).value;
_realmLib.invokeGetBool(() => _realmLib.realm_get_class(realm.handle._pointer, classKey, classInfo));
final name = classInfo.ref.name.cast<Utf8>().toDartString();
final baseType = ObjectType.values.firstWhere((element) => element.flags == classInfo.ref.flags,
orElse: () => throw RealmError('No object type found for flags ${classInfo.ref.flags}'));
final schema =
_getSchemaForClassKey(realm, classKey, name, baseType, arena, expectedSize: classInfo.ref.num_properties + classInfo.ref.num_computed_properties);
schemas.add(schema);
}
return RealmSchema(schemas);
}
SchemaObject _getSchemaForClassKey(Realm realm, int classKey, String name, ObjectType baseType, Arena arena, {int expectedSize = 10}) {
final actualCount = arena<Size>();
final propertiesPtr = arena<realm_property_info>(expectedSize);
_realmLib.invokeGetBool(() => _realmLib.realm_get_class_properties(realm.handle._pointer, classKey, propertiesPtr, expectedSize, actualCount));
if (expectedSize < actualCount.value) {
// The supplied array was too small - resize it
arena.free(propertiesPtr);
return _getSchemaForClassKey(realm, classKey, name, baseType, arena, expectedSize: actualCount.value);
}
final result = <SchemaProperty>[];
for (var i = 0; i < actualCount.value; i++) {
final property = propertiesPtr.elementAt(i).ref.toSchemaProperty();
result.add(property);
}
late Type type;
switch (baseType) {
case ObjectType.realmObject:
type = RealmObject;
break;
case ObjectType.embeddedObject:
type = EmbeddedObject;
break;
case ObjectType.asymmetricObject:
type = AsymmetricObject;
break;
default:
throw RealmError('$baseType is not supported yet');
}
return SchemaObject(baseType, type, name, result);
}
void deleteRealmFiles(String path) {
using((Arena arena) {
final realm_deleted = arena<Bool>();
_realmLib.invokeGetBool(() => _realmLib.realm_delete_files(path.toCharPtr(arena), realm_deleted), "Error deleting realm at path $path");
});
}
String getFilesPath() {
return _realmLib.realm_dart_get_files_path().cast<Utf8>().toRealmDartString()!;
}
String getDeviceName() {
if (Platform.isAndroid || Platform.isIOS) {
return _realmLib.realm_dart_get_device_name().cast<Utf8>().toRealmDartString()!;
}
return "";
}
String getDeviceVersion() {
if (Platform.isAndroid || Platform.isIOS) {
return _realmLib.realm_dart_get_device_version().cast<Utf8>().toRealmDartString()!;
}
return "";
}
String getRealmLibraryCpuArchitecture() {
return _realmLib.realm_get_library_cpu_arch().cast<Utf8>().toDartString();
}
void closeRealm(Realm realm) {
_realmLib.invokeGetBool(() => _realmLib.realm_close(realm.handle._pointer), "Realm close failed");
}
bool isRealmClosed(Realm realm) {
return _realmLib.realm_is_closed(realm.handle._pointer);
}
void beginWrite(Realm realm) {
_realmLib.invokeGetBool(() => _realmLib.realm_begin_write(realm.handle._pointer), "Could not begin write");
}
void commitWrite(Realm realm) {
_realmLib.invokeGetBool(() => _realmLib.realm_commit(realm.handle._pointer), "Could not commit write");
}
Future<void> beginWriteAsync(Realm realm, CancellationToken? ct) {
int? id;
final completer = CancellableCompleter<void>(ct, onCancel: () {
if (id != null) {
realmCore._cancelAsync(realm, id!);
}
});
if (ct?.isCancelled != true) {
using((arena) {
final transaction_id = arena<UnsignedInt>();
_realmLib.invokeGetBool(() => _realmLib.realm_async_begin_write(
realm.handle._pointer,
Pointer.fromFunction(_completeAsyncBeginWrite),
completer.toPersistentHandle(),
_realmLib.addresses.realm_dart_delete_persistent_handle,
true,
transaction_id,
));
id = transaction_id.value;
});
}
return completer.future;
}
Future<void> commitWriteAsync(Realm realm, CancellationToken? ct) {
int? id;
final completer = CancellableCompleter<void>(ct, onCancel: () {
if (id != null) {
realmCore._cancelAsync(realm, id!);
}
});
if (ct?.isCancelled != true) {
using((arena) {
final transaction_id = arena<UnsignedInt>();
_realmLib.invokeGetBool(() => _realmLib.realm_async_commit(
realm.handle._pointer,
Pointer.fromFunction(_completeAsyncCommit),
completer.toPersistentHandle(),
_realmLib.addresses.realm_dart_delete_persistent_handle,
false,
transaction_id,
));
id = transaction_id.value;
});
}
return completer.future;
}
bool _cancelAsync(Realm realm, int cancellationId) {
return using((Arena arena) {
final didCancel = arena<Bool>();
_realmLib.invokeGetBool(() => _realmLib.realm_async_cancel(realm.handle._pointer, cancellationId, didCancel));
return didCancel.value;
});
}
static void _completeAsyncBeginWrite(Pointer<Void> userdata) {
final Completer<void> completer = userdata.toObject();
completer.complete();
}
static void _completeAsyncCommit(Pointer<Void> userdata, bool error, Pointer<Char> description) {
final Completer<void> completer = userdata.toObject();
if (error) {
completer.completeError(RealmException(description.cast<Utf8>().toDartString()));
} else {
completer.complete();
}
}
bool getIsWritable(Realm realm) {
return _realmLib.realm_is_writable(realm.handle._pointer);
}
void rollbackWrite(Realm realm) {
_realmLib.invokeGetBool(() => _realmLib.realm_rollback(realm.handle._pointer), "Could not rollback write");
}
bool realmRefresh(Realm realm) {
return using((Arena arena) {
final did_refresh = arena<Bool>();
_realmLib.invokeGetBool(() => _realmLib.realm_refresh(realm.handle._pointer, did_refresh), "Could not refresh");
return did_refresh.value;
});
}
Future<bool> realmRefreshAsync(Realm realm) async {
final completer = Completer<bool>();
final callback = Pointer.fromFunction<Void Function(Pointer<Void>)>(_realmRefreshAsyncCallback);
Pointer<Void> completerPtr = _realmLib.realm_dart_object_to_persistent_handle(completer);
Pointer<realm_refresh_callback_token> result = _realmLib.realm_add_realm_refresh_callback(
realm.handle._pointer, callback.cast(), completerPtr, _realmLib.addresses.realm_dart_delete_persistent_handle);
if (result == nullptr) {
return Future<bool>.value(false);
}
return completer.future;
}
static void _realmRefreshAsyncCallback(Pointer<Void> userdata) {
if (userdata == nullptr) {
return;
}
final completer = _realmLib.realm_dart_persistent_handle_to_object(userdata) as Completer<bool>;
completer.complete(true);
}
RealmObjectMetadata getObjectMetadata(Realm realm, SchemaObject schema) {
return using((Arena arena) {
final found = arena<Bool>();
final classInfo = arena<realm_class_info_t>();
_realmLib.invokeGetBool(() => _realmLib.realm_find_class(realm.handle._pointer, schema.name.toCharPtr(arena), found, classInfo),
"Error getting class ${schema.name} from realm at ${realm.config.path}");
if (!found.value) {
throwLastError("Class ${schema.name} not found in ${realm.config.path}");
}
final primaryKey = classInfo.ref.primary_key.cast<Utf8>().toRealmDartString(treatEmptyAsNull: true);
return RealmObjectMetadata(schema, classInfo.ref.key, _getPropertiesMetadata(realm, classInfo.ref.key, primaryKey, arena));
});
}
Map<String, RealmPropertyMetadata> getPropertiesMetadata(Realm realm, int classKey, String? primaryKeyName) {
return using((Arena arena) {
return _getPropertiesMetadata(realm, classKey, primaryKeyName, arena);
});
}
Map<String, RealmPropertyMetadata> _getPropertiesMetadata(Realm realm, int classKey, String? primaryKeyName, Arena arena) {
final propertyCountPtr = arena<Size>();
_realmLib.invokeGetBool(
() => _realmLib.realm_get_property_keys(realm.handle._pointer, classKey, nullptr, 0, propertyCountPtr), "Error getting property count");
var propertyCount = propertyCountPtr.value;
final propertiesPtr = arena<realm_property_info_t>(propertyCount);
_realmLib.invokeGetBool(() => _realmLib.realm_get_class_properties(realm.handle._pointer, classKey, propertiesPtr, propertyCount, propertyCountPtr),
"Error getting class properties.");
propertyCount = propertyCountPtr.value;
Map<String, RealmPropertyMetadata> result = <String, RealmPropertyMetadata>{};
for (var i = 0; i < propertyCount; i++) {
final property = propertiesPtr.elementAt(i);
final propertyName = property.ref.name.cast<Utf8>().toRealmDartString()!;
final objectType = property.ref.link_target.cast<Utf8>().toRealmDartString(treatEmptyAsNull: true);
final linkOriginProperty = property.ref.link_origin_property_name.cast<Utf8>().toRealmDartString(treatEmptyAsNull: true);
final isNullable = property.ref.flags & realm_property_flags.RLM_PROPERTY_NULLABLE != 0;
final isPrimaryKey = propertyName == primaryKeyName;
final propertyMeta = RealmPropertyMetadata(property.ref.key, objectType, linkOriginProperty, RealmPropertyType.values.elementAt(property.ref.type),
isNullable, isPrimaryKey, RealmCollectionType.values.elementAt(property.ref.collection_type));
result[propertyName] = propertyMeta;
}
return result;
}
RealmObjectHandle createRealmObject(Realm realm, int classKey) {
final realmPtr = _realmLib.invokeGetPointer(() => _realmLib.realm_object_create(realm.handle._pointer, classKey));
return RealmObjectHandle._(realmPtr, realm.handle);
}
RealmObjectHandle createEmbeddedObject(RealmObjectBase obj, int propertyKey) {
final objectPtr = _realmLib.invokeGetPointer(() => _realmLib.realm_set_embedded(obj.handle._pointer, propertyKey));
return RealmObjectHandle._(objectPtr, obj.realm.handle);
}
Tuple<RealmObjectHandle, int> getEmbeddedParent(EmbeddedObject obj) {
return using((Arena arena) {
final parentPtr = arena<Pointer<realm_object>>();
final classKeyPtr = arena<Uint32>();