/
Realm.cs
1957 lines (1707 loc) · 93.6 KB
/
Realm.cs
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 2016 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using MongoDB.Bson;
using Realms.Dynamic;
using Realms.Exceptions;
using Realms.Extensions;
using Realms.Helpers;
using Realms.Logging;
using Realms.Native;
using Realms.Schema;
using Realms.Sync;
using Realms.Weaving;
namespace Realms
{
/// <summary>
/// A Realm instance (also referred to as a Realm) represents a Realm database.
/// <br/>
/// <b>Warning</b>: Non-frozen Realm instances are not thread safe and can not be shared across threads.
/// You must call <see cref="GetInstance(RealmConfigurationBase)"/> on each thread in which you want to interact with the Realm.
/// </summary>
public class Realm : IDisposable
{
#region static
/// <summary>
/// Gets or sets a value indicating whether to use the legacy representation when storing Guid values in the database.
/// </summary>
/// <remarks>
/// In versions prior to 10.10.0, the .NET SDK had a bug where it would store Guid values with architecture-specific byte ordering
/// (little-endian for most modern CPUs) while the database query engine and Sync would always treat them as big-endian. This manifests
/// as different string representations between the SDK and the database - e.g. "f2952191-a847-41c3-8362-497f92cb7d24" instead of
/// "912195f2-47a8-c341-8362-497f92cb7d24" (notice the swapped bytes in the first 3 components). Starting with 10.10.0, big-endian
/// representation is the default one and a seamless one-time migration is provided for local (non-sync) Realms. The first time a
/// Realm is opened, all properties holding a Guid value will be updated from little-endian to big-endian format and the .NET SDK
/// will treat them as such. There should be no noticeable change when reading/writing data from the SDK, but you should see consistent
/// values when accessing the Realm file from Realm Studio or other SDKs.
/// <br/>
/// For synchronized Realms, such a migration is impossible due to the distributed nature of the data. Therefore, the assumption
/// is that the Guid representation in Atlas if authoritative and the SDK values should be updated to match it. THIS MEANS THAT THE
/// SDK WILL START REPORTING A DIFFERENT STRING REPRESENTATION OF EXISTING GUID DATA COMPARED TO pre-10.10.0. If you are querying
/// 3rd party systems from the SDK, you might see unexpected results. To preserve the existing behavior (little-endian in the SDK,
/// big-endian in Atlas), set this value to <c>true</c> and reach out to the Realm support team (https://support.mongodb.com) for
/// help with migrating your data to the new format.
/// </remarks>
[Obsolete("It is strongly advised to migrate to the new Guid representation as soon as possible to avoid data inconsistency.")]
public static bool UseLegacyGuidRepresentation { get; set; }
/// <summary>
/// Factory for obtaining a <see cref="Realm"/> instance for this thread.
/// </summary>
/// <param name="databasePath">
/// Path to the realm, must be a valid full path for the current platform, relative subdirectory, or just filename.
/// </param>
/// <remarks>
/// If you specify a relative path, sandboxing by the OS may cause failure if you specify anything other than a subdirectory.
/// </remarks>
/// <returns>A <see cref="Realm"/> instance.</returns>
/// <exception cref="RealmFileAccessErrorException">
/// Thrown if the file system returns an error preventing file creation.
/// </exception>
public static Realm GetInstance(string databasePath)
{
return GetInstance(new RealmConfiguration(databasePath));
}
/// <summary>
/// Factory for obtaining a <see cref="Realm"/> instance for this thread.
/// </summary>
/// <param name="config">Optional configuration.</param>
/// <returns>A <see cref="Realm"/> instance.</returns>
/// <exception cref="RealmFileAccessErrorException">
/// Thrown if the file system returns an error preventing file creation.
/// </exception>
public static Realm GetInstance(RealmConfigurationBase? config = null)
{
config ??= RealmConfiguration.DefaultConfiguration;
return config.CreateRealm();
}
/// <summary>
/// Factory for asynchronously obtaining a <see cref="Realm"/> instance.
/// </summary>
/// <remarks>
/// If the configuration is <see cref="SyncConfigurationBase"/>, the realm will be downloaded and fully
/// synchronized with the server prior to the completion of the returned Task object.
/// Otherwise this method will perform any migrations on a background thread before returning an
/// opened instance to the calling thread.
/// </remarks>
/// <returns>
/// An awaitable <see cref="Task{T}"/> that is completed once the remote realm is fully synchronized or
/// after migrations are executed if it's a local realm.
/// </returns>
/// <param name="config">A configuration object that describes the realm.</param>
/// <param name="cancellationToken">An optional cancellation token that can be used to cancel the work.</param>
public static Task<Realm> GetInstanceAsync(RealmConfigurationBase? config = null, CancellationToken cancellationToken = default)
{
config ??= RealmConfiguration.DefaultConfiguration;
return config.CreateRealmAsync(cancellationToken);
}
/// <summary>
/// Compacts a Realm file. A Realm file usually contains free/unused space. This method removes this free space and the file size is thereby reduced. Objects within the Realm file are untouched.
/// </summary>
/// <remarks>
/// The realm file must not be open on other threads.
/// The file system should have free space for at least a copy of the Realm file.
/// This method must not be called inside a transaction.
/// The Realm file is left untouched if any file operation fails.
/// </remarks>
/// <param name="config">Optional configuration.</param>
/// <returns><c>true</c> if successful, <c>false</c> if any file operation failed.</returns>
public static bool Compact(RealmConfigurationBase? config = null)
{
using var realm = GetInstance(config);
if (config is SyncConfigurationBase)
{
// For synchronized Realms, shutdown the session, otherwise Compact will fail.
var session = realm.SyncSession;
session.CloseHandle(waitForShutdown: true);
}
return realm.SharedRealmHandle.Compact();
}
/// <summary>
/// Deletes all files associated with a given Realm if the Realm exists and is not open.
/// </summary>
/// <remarks>
/// The Realm file must not be open on other threads.<br/>
/// All but the .lock file will be deleted by this.
/// </remarks>
/// <param name="configuration">A <see cref="RealmConfigurationBase"/> which supplies the realm path.</param>
/// <exception cref="RealmInUseException">Thrown if the Realm is still open.</exception>
public static void DeleteRealm(RealmConfigurationBase configuration)
{
Argument.NotNull(configuration, nameof(configuration));
SharedRealmHandle.DeleteFiles(configuration.DatabasePath);
}
#endregion static
private WeakReference<SubscriptionSet>? _subscriptionRef;
private State _state;
private SessionProvider? _sessionProvider;
private Transaction? _activeTransaction;
internal readonly SharedRealmHandle SharedRealmHandle;
internal readonly RealmMetadata Metadata;
internal readonly bool IsInMigration;
/// <summary>
/// Gets an object encompassing the dynamic API for this Realm instance.
/// </summary>
/// <value>A <see cref="Dynamic"/> instance that wraps this Realm.</value>
[Preserve]
public Dynamic DynamicApi => new(this);
/// <summary>
/// Gets a value indicating whether there is an active write transaction associated
/// with this Realm.
/// </summary>
/// <value><c>true</c> if the Realm is in transaction; <c>false</c> otherwise.</value>
/// <seealso cref="BeginWrite"/>
/// <seealso cref="Transaction"/>
public bool IsInTransaction
{
get
{
ThrowIfDisposed();
return SharedRealmHandle.IsInTransaction();
}
}
/// <summary>
/// Gets a value indicating whether this Realm is frozen. Frozen Realms are immutable
/// and will not update when writes are made to the database. Unlike live Realms, frozen
/// Realms can be used across threads.
/// </summary>
/// <value><c>true</c> if the Realm is frozen and immutable; <c>false</c> otherwise.</value>
/// <see cref="Freeze"/>
public bool IsFrozen { get; }
/// <summary>
/// Gets the <see cref="RealmSchema"/> instance that describes all the types that can be stored in this <see cref="Realm"/>.
/// </summary>
/// <value>The Schema of the Realm.</value>
public RealmSchema Schema { get; }
/// <summary>
/// Gets the <see cref="RealmConfigurationBase"/> that controls this realm's path and other settings.
/// </summary>
/// <value>The Realm's configuration.</value>
public RealmConfigurationBase Config { get; }
/// <summary>
/// Gets the <see cref="Session"/> for this <see cref="Realm"/>.
/// </summary>
/// <exception cref="NotSupportedException">
/// Thrown if the Realm has not been opened with a <see cref="FlexibleSyncConfiguration"/> or
/// <see cref="PartitionSyncConfiguration"/>.
/// </exception>
/// <value>
/// The <see cref="Session"/> that is responsible for synchronizing with MongoDB Atlas
/// if the Realm instance was created with a <see cref="FlexibleSyncConfiguration"/> or
/// <see cref="PartitionSyncConfiguration"/>. If this is a local or in-memory Realm, a
/// <see cref="NotSupportedException"/> will be thrown.
/// </value>
public Session SyncSession
{
get
{
ThrowIfDisposed();
if (Config is not SyncConfigurationBase)
{
throw new NotSupportedException("Realm.SyncSession is only valid for synchronized Realms (i.e. ones that are opened with FlexibleSyncConfiguration or PartitionSyncConfiguration).");
}
_sessionProvider ??= new SessionProvider(SharedRealmHandle);
return _sessionProvider.GetSession();
}
}
/// <summary>
/// Gets the <see cref="SubscriptionSet"/> representing the active subscriptions for this <see cref="Realm"/>.
/// </summary>
/// <exception cref="NotSupportedException">Thrown if the Realm has not been opened with a <see cref="FlexibleSyncConfiguration"/>.</exception>
/// <value>
/// The <see cref="SubscriptionSet"/> containing the query subscriptions that the server is using to decide which objects to
/// synchronize with the local <see cref="Realm"/>. If the Realm was not created with a <see cref="FlexibleSyncConfiguration"/>,
/// this will throw a <see cref="NotSupportedException"/>.
/// </value>
public SubscriptionSet Subscriptions
{
get
{
ThrowIfDisposed();
if (Config is not FlexibleSyncConfiguration)
{
throw new NotSupportedException("Realm.Subscriptions is only valid for flexible sync Realms (i.e. ones that are opened with FlexibleSyncConfiguration).");
}
// If the last subscription ref is alive and its version matches the current subscription
// version, we return it. Otherwise, we create a new set and replace the existing one.
if (_subscriptionRef != null && _subscriptionRef.TryGetTarget(out var existingSet))
{
var currentVersion = SharedRealmHandle.GetSubscriptionsVersion();
if (existingSet.Version >= currentVersion)
{
return existingSet;
}
}
var handle = SharedRealmHandle.GetSubscriptions();
var set = new SubscriptionSet(handle);
_subscriptionRef = new WeakReference<SubscriptionSet>(set);
return set;
}
}
internal Realm(SharedRealmHandle sharedRealmHandle, RealmConfigurationBase config, RealmSchema schema, RealmMetadata? metadata = null, bool isInMigration = false)
{
Config = config;
IsInMigration = isInMigration;
State? state = null;
if (config.EnableCache && sharedRealmHandle.OwnsNativeRealm)
{
var statePtr = sharedRealmHandle.GetManagedStateHandle();
if (statePtr != IntPtr.Zero)
{
state = GCHandle.FromIntPtr(statePtr).Target as State;
}
}
if (state is null)
{
state = new State();
sharedRealmHandle.SetManagedStateHandle(state);
}
_state = state;
_state.AddRealm(this);
SharedRealmHandle = sharedRealmHandle;
Metadata = metadata ?? new RealmMetadata(schema.Select(CreateRealmObjectMetadata));
Schema = schema;
IsFrozen = SharedRealmHandle.IsFrozen;
}
private Metadata CreateRealmObjectMetadata(ObjectSchema schema)
{
var tableKey = SharedRealmHandle.GetTableKey(schema.Name);
IRealmObjectHelper helper;
if (schema.Type != null && !Config.IsDynamic)
{
var wovenAtt = schema.Type.GetCustomAttribute<WovenAttribute>();
if (wovenAtt is null)
{
throw new RealmException($"Fody not properly installed. {schema.Type.FullName} is a RealmObjectBase but has not been woven.");
}
helper = (IRealmObjectHelper)Activator.CreateInstance(wovenAtt.HelperType)!;
}
else
{
helper = DynamicRealmObjectHelper.Instance(schema);
}
var initPropertyMap = new Dictionary<string, IntPtr>(schema.Count);
var persistedProperties = -1;
var computedProperties = -1;
// We're taking advantage of the fact OS keeps property indices aligned
// with the property indices in ObjectSchema
foreach (var prop in schema)
{
var index = prop.Type.IsComputed() ? ++computedProperties : ++persistedProperties;
initPropertyMap[prop.Name] = (IntPtr)index;
}
return new Metadata(tableKey, helper, initPropertyMap, schema);
}
/// <summary>
/// Handler type used by <see cref="RealmChanged"/>.
/// </summary>
/// <param name="sender">The <see cref="Realm"/> which has changed.</param>
/// <param name="e">Currently an empty argument, in the future may indicate more details about the change.</param>
public delegate void RealmChangedEventHandler(Realm sender, EventArgs e);
[SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:Element should begin with upper-case letter", Justification = "This is the private event - the public is uppercased.")]
private event RealmChangedEventHandler? _realmChanged;
/// <summary>
/// Triggered when a Realm has changed (i.e. a <see cref="Transaction"/> was committed).
/// </summary>
public event RealmChangedEventHandler? RealmChanged
{
add
{
ThrowIfFrozen("It is not possible to add/remove a change listener to a frozen Realm since it never changes.");
_realmChanged += value;
}
remove
{
ThrowIfFrozen("It is not possible to add/remove a change listener to a frozen Realm since it never changes.");
_realmChanged -= value;
}
}
private void NotifyChanged(EventArgs e)
{
_realmChanged?.Invoke(this, e);
}
/// <summary>
/// Triggered when a Realm-level exception has occurred.
/// </summary>
public event EventHandler<ErrorEventArgs>? Error;
internal void NotifyError(Exception ex)
{
if (Error is null)
{
Logger.LogDefault(LogLevel.Error, "A realm-level exception has occurred. To handle and react to those, subscribe to the Realm.Error event.");
}
Error?.Invoke(this, new ErrorEventArgs(ex));
}
/// <summary>
/// Gets a value indicating whether the instance has been closed via <see cref="Dispose()"/>. If <c>true</c>, you
/// should not call methods on that instance.
/// </summary>
/// <value><c>true</c> if closed, <c>false</c> otherwise.</value>
public bool IsClosed => SharedRealmHandle.IsClosed;
/// <summary>
/// Disposes the current instance and closes the native Realm if this is the last remaining
/// instance holding a reference to it.
/// </summary>
public void Dispose()
{
if (!IsClosed)
{
_activeTransaction?.Dispose();
_state.RemoveRealm(this, closeOnEmpty: SharedRealmHandle.OwnsNativeRealm);
_state = null!;
SharedRealmHandle.Close(); // Note: this closes the *handle*, it does not trigger realm::Realm::close().
}
}
/// <summary>
/// Returns a frozen (immutable) snapshot of this Realm.
/// <para/>
/// A frozen Realm is an immutable snapshot view of a particular version of a
/// Realm's data. Unlike normal <see cref="Realm"/> instances, it does not live-update to
/// reflect writes made to the Realm, and can be accessed from any thread. Writing
/// to a frozen Realm is not allowed, and attempting to begin a write transaction
/// will throw an exception.
/// <para/>
/// All objects and collections read from a frozen Realm will also be frozen.
/// <para/>
/// Note: Keeping a large number of frozen Realms with different versions alive can have a negative impact on the filesize
/// of the underlying database. In order to avoid such a situation it is possible to set <see cref="RealmConfigurationBase.MaxNumberOfActiveVersions"/>.
/// </summary>
/// <returns>A frozen <see cref="Realm"/> instance.</returns>
public Realm Freeze()
{
if (IsFrozen)
{
return this;
}
var handle = SharedRealmHandle.Freeze();
return new Realm(handle, Config, Schema, Metadata);
}
private void ThrowIfDisposed()
{
if (IsClosed)
{
throw new ObjectDisposedException(typeof(Realm).FullName, "Cannot access a closed Realm.");
}
}
private void ThrowIfFrozen(string message)
{
if (IsFrozen)
{
throw new RealmFrozenException(message);
}
}
/// <inheritdoc />
public override bool Equals(object? obj) => Equals(obj as Realm);
private bool Equals(Realm? other)
{
if (other is null)
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return Config.Equals(other.Config) && IsClosed == other.IsClosed;
}
/// <summary>
/// Determines whether this instance is the same core instance as the passed in argument.
/// </summary>
/// <remarks>
/// You can, and should, have multiple instances open on different threads which have the same path and open the same Realm.
/// </remarks>
/// <returns><c>true</c> if this instance is the same core instance; otherwise, <c>false</c>.</returns>
/// <param name="other">The Realm to compare with the current Realm.</param>
public bool IsSameInstance(Realm other)
{
ThrowIfDisposed();
Argument.NotNull(other, nameof(other));
return SharedRealmHandle == other.SharedRealmHandle || SharedRealmHandle.IsSameInstance(other.SharedRealmHandle);
}
/// <inheritdoc/>
public override int GetHashCode()
{
ThrowIfDisposed();
return (int)((long)SharedRealmHandle.DangerousGetHandle() % int.MaxValue);
}
internal IRealmObjectBase MakeObject(Metadata metadata, ObjectHandle objectHandle)
{
var ret = metadata.Helper.CreateInstance();
ret.CreateAndSetAccessor(objectHandle, this, metadata);
return ret;
}
internal RealmMetadata MergeSchema(RealmSchema schema)
{
Metadata.Add(schema.Select(CreateRealmObjectMetadata));
return Metadata;
}
/// <summary>
/// This <see cref="Realm"/> will start managing an <see cref="IRealmObject"/> which has been created as a standalone object.
/// </summary>
/// <typeparam name="T">
/// The Type T must not only be a <see cref="IRealmObject"/> but also have been processed by the Fody weaver,
/// so it has persistent properties.
/// </typeparam>
/// <param name="obj">Must be a standalone object, <c>null</c> not allowed.</param>
/// <param name="update">If <c>true</c>, and an object with the same primary key already exists, performs an update.</param>
/// <exception cref="RealmInvalidTransactionException">
/// If you invoke this when there is no write <see cref="Transaction"/> active on the <see cref="Realm"/>.
/// </exception>
/// <exception cref="RealmObjectManagedByAnotherRealmException">
/// You can't manage an object with more than one <see cref="Realm"/>.
/// </exception>
/// <remarks>
/// If the object is already managed by this <see cref="Realm"/>, this method does nothing.
/// This method modifies the object in-place, meaning that after it has run, <paramref name="obj"/> will be managed.
/// Returning it is just meant as a convenience to enable fluent syntax scenarios.
/// </remarks>
/// <returns>The passed object, so that you can write <c>var person = realm.Add(new Person { Id = 1 });</c>.</returns>
public T Add<T>(T obj, bool update = false)
where T : IRealmObject
{
ThrowIfDisposed();
Argument.NotNull(obj, nameof(obj));
Argument.Ensure(obj.IsValid, "Cannot add the object to the realm because it has been removed.", nameof(obj));
// This is not obsoleted because the compiler will always pick it for specific types, generating a bunch of warnings
AddInternal(obj, obj.GetType(), update);
return obj;
}
/// <summary>
/// Add a collection of standalone <see cref="IRealmObject">RealmObjects</see> to this <see cref="Realm"/>.
/// </summary>
/// <typeparam name="T">
/// The Type T must not only be a <see cref="IRealmObject"/> but also have been processed by the Fody weaver,
/// so it has persistent properties.
/// </typeparam>
/// <param name="objs">A collection of <see cref="IRealmObject"/> instances that will be added to this <see cref="Realm"/>.</param>
/// <param name="update">If <c>true</c>, and an object with the same primary key already exists, performs an update.</param>
/// <exception cref="RealmInvalidTransactionException">
/// If you invoke this when there is no write <see cref="Transaction"/> active on the <see cref="Realm"/>.
/// </exception>
/// <exception cref="RealmObjectManagedByAnotherRealmException">
/// You can't manage an object with more than one <see cref="Realm"/>.
/// </exception>
/// <remarks>
/// If the collection contains items that are already managed by this <see cref="Realm"/>, they will be ignored.
/// This method modifies the objects in-place, meaning that after it has run, all items in <paramref name="objs"/> will be managed.
/// </remarks>
public void Add<T>(IEnumerable<T> objs, bool update = false)
where T : IRealmObject
{
ThrowIfDisposed();
Argument.NotNull(objs, nameof(objs));
foreach (var obj in objs)
{
Argument.Ensure(obj != null, $"{nameof(objs)} must not contain null objects.", nameof(objs));
Argument.Ensure(obj.IsValid, $"{nameof(objs)} must not contain removed objects.", nameof(objs));
}
foreach (var obj in objs)
{
AddInternal(obj, obj.GetType(), update);
}
}
/// <summary>
/// This <see cref="Realm"/> will start managing an <see cref="IAsymmetricObject"/> which has been created as a standalone object.
/// </summary>
/// <typeparam name="T">
/// The Type T must not only be a <see cref="IAsymmetricObject"/> but also have been processed by the Fody weaver,
/// so it has persistent properties.
/// </typeparam>
/// <param name="obj">Must be a standalone <see cref="IAsymmetricObject"/>, <c>null</c> not allowed.</param>
/// <exception cref="RealmInvalidTransactionException">
/// If you invoke this when there is no write <see cref="Transaction"/> active on the <see cref="Realm"/>.
/// </exception>
/// <exception cref="RealmObjectManagedByAnotherRealmException">
/// You can't manage an object with more than one <see cref="Realm"/>.
/// </exception>
/// <remarks>
/// If the object is already managed by this <see cref="Realm"/>, this method does nothing.
/// This method modifies the object in-place,
/// meaning that after it has run, <see cref="IAsymmetricObject"/> will be managed.
/// Once an <see cref="IAsymmetricObject"/> becomes managed dereferencing any property
/// of the original <see cref="IAsymmetricObject"/> reference throws an exception.
/// </remarks>
public void Add<T>(T obj)
where T : IAsymmetricObject
{
ThrowIfDisposed();
Argument.NotNull(obj, nameof(obj));
Argument.Ensure(!obj.IsManaged, $"{nameof(obj)} must not be already managed by a Realm.", nameof(obj));
AddInternal(obj, obj.GetType(), update: false);
}
/// <summary>
/// Add a collection of standalone <see cref="IAsymmetricObject">AsymmetricObjects</see> to this <see cref="Realm"/>.
/// </summary>
/// <typeparam name="T">
/// The Type T must not only be a <see cref="IAsymmetricObject"/> but also have been processed by the Fody weaver,
/// so it has persistent properties.
/// </typeparam>
/// <param name="objs">A collection of <see cref="IAsymmetricObject"/> instances that will be added to this <see cref="Realm"/>.</param>
/// <exception cref="RealmInvalidTransactionException">
/// If you invoke this when there is no write <see cref="Transaction"/> active on the <see cref="Realm"/>.
/// </exception>
/// <exception cref="RealmObjectManagedByAnotherRealmException">
/// You can't manage an object with more than one <see cref="Realm"/>.
/// </exception>
/// <remarks>
/// If the collection contains items that are already managed by this <see cref="Realm"/>, they will be ignored.
/// This method modifies the objects in-place, meaning that after it has run, all items in the collection will be managed.
/// Once an <see cref="IAsymmetricObject"/> becomes managed and the transaction is committed,
/// dereferencing any property of the original <see cref="IAsymmetricObject"/> reference throw an exception.
/// Hence, none of the properties of the elements in the collection can be dereferenced anymore after the transaction.
/// </remarks>
public void Add<T>(IEnumerable<T> objs)
where T : IAsymmetricObject
{
ThrowIfDisposed();
Argument.NotNull(objs, nameof(objs));
foreach (var obj in objs)
{
Argument.Ensure(obj != null, $"{nameof(objs)} must not contain null values.", nameof(objs));
Argument.Ensure(!obj.IsManaged, $"{nameof(objs)} must not contain already managed objects by a Realm.", nameof(objs));
}
foreach (var obj in objs)
{
AddInternal(obj, obj.GetType(), update: false);
}
}
internal void ManageEmbedded(IEmbeddedObject obj, ObjectHandle handle)
{
var objectType = obj.GetType();
var objectName = objectType.GetMappedOrOriginalName();
Argument.Ensure(Metadata.TryGetValue(objectName, out var metadata), $"The class {objectType.Name} is not in the limited set of classes for this realm", nameof(obj));
obj.CreateAndSetAccessor(handle, this, metadata, copyToRealm: true, update: false, skipDefaults: true);
}
private void AddInternal<T>(T obj, Type objectType, bool update)
where T : IRealmObjectBase
{
if (objectType.IsEmbeddedObject())
{
throw new ArgumentException("EmbeddedObjects can't be added as standalone objects.");
}
if (!ShouldAddNewObject(obj))
{
return;
}
var objectName = objectType.GetMappedOrOriginalName();
Argument.Ensure(Metadata.TryGetValue(objectName, out var metadata), $"The class {objectType.Name} is not in the limited set of classes for this realm", nameof(objectType));
ObjectHandle objectHandle;
bool isNew;
if (metadata.Helper.TryGetPrimaryKeyValue(obj, out var primaryKey))
{
var pkProperty = metadata.Schema.PrimaryKeyProperty!.Value;
objectHandle = SharedRealmHandle.CreateObjectWithPrimaryKey(pkProperty, primaryKey, metadata.TableKey, objectName, update, out isNew);
}
else
{
isNew = true; // Objects without PK are always new
objectHandle = SharedRealmHandle.CreateObject(metadata.TableKey);
}
obj.CreateAndSetAccessor(objectHandle, this, metadata, copyToRealm: true, update: update, skipDefaults: isNew);
}
private bool ShouldAddNewObject(IRealmObjectBase obj)
{
Argument.NotNull(obj, nameof(obj));
if (obj.IsManaged)
{
if (IsSameInstance(obj.Realm))
{
// Already managed by this realm, so nothing to do.
return false;
}
throw new RealmObjectManagedByAnotherRealmException("Cannot start to manage an object with a realm when it's already managed by another realm");
}
return true;
}
/// <summary>
/// Begins a write transaction for this Realm.
/// </summary>
/// <example>
/// <code>
/// using (var trans = realm.BeginWrite())
/// {
/// realm.Add(new Dog
/// {
/// Name = "Rex"
/// });
/// trans.Commit();
/// }
/// </code>
/// </example>
/// <returns>A transaction in write mode, which is required for any creation or modification of objects persisted in a <see cref="Realm"/>.</returns>
public Transaction BeginWrite()
{
ThrowIfDisposed();
ThrowIfFrozen("Starting a write transaction on a frozen Realm is not allowed.");
SharedRealmHandle.BeginTransaction();
Debug.Assert(_activeTransaction is null, "There should be no active transaction");
return _activeTransaction = new Transaction(this);
}
/// <summary>
/// Execute an action inside a temporary <see cref="Transaction"/>. If no exception is thrown, the <see cref="Transaction"/>
/// will be committed.
/// </summary>
/// <remarks>
/// Creates its own temporary <see cref="Transaction"/> and commits it after running the lambda passed to <paramref name="action"/>.
/// Be careful of wrapping multiple single property updates in multiple <see cref="Write"/> calls.
/// It is more efficient to update several properties or even create multiple objects in a single <see cref="Write"/>,
/// unless you need to guarantee finer-grained updates.
/// </remarks>
/// <example>
/// <code>
/// realm.Write(() =>
/// {
/// realm.Add(new Dog
/// {
/// Name = "Eddie",
/// Age = 5
/// });
/// });
/// </code>
/// </example>
/// <param name="action">
/// Action to execute inside a <see cref="Transaction"/>, creating, updating, or removing objects.
/// </param>
public void Write(Action action)
{
Argument.NotNull(action, nameof(action));
Write(() =>
{
action();
return true;
});
}
/// <summary>
/// Execute a delegate inside a temporary <see cref="Transaction"/>. If no exception is thrown, the <see cref="Transaction"/>
/// will be committed.
/// </summary>
/// <remarks>
/// Creates its own temporary <see cref="Transaction"/> and commits it after running the lambda passed to <paramref name="function"/>.
/// Be careful of wrapping multiple single property updates in multiple <see cref="Write"/> calls.
/// It is more efficient to update several properties or even create multiple objects in a single <see cref="Write"/>,
/// unless you need to guarantee finer-grained updates.
/// </remarks>
/// <example>
/// <code>
/// var dog = realm.Write(() =>
/// {
/// return realm.Add(new Dog
/// {
/// Name = "Eddie",
/// Age = 5
/// });
/// });
/// </code>
/// </example>
/// <param name="function">
/// Delegate with one return value to execute inside a <see cref="Transaction"/>, creating, updating, or removing objects.
/// </param>
/// <typeparam name="T">The type returned by the input delegate.</typeparam>
/// <returns>The return value of <paramref name="function"/>.</returns>
public T Write<T>(Func<T> function)
{
ThrowIfDisposed();
Argument.NotNull(function, nameof(function));
using var transaction = BeginWrite();
var result = function();
transaction.Commit();
return result;
}
/// <summary>
/// Asynchronously begins a write transaction for this Realm.
/// </summary>
/// <remarks>
/// This method asynchronously acquires the write lock and then dispatches the continuation on the original
/// thread the Realm was opened on. The transaction can then be committed either asynchronously or
/// synchronously.
/// <br/>
/// When invoked on a thread without SynchronizationContext (i.e. typically background threads), this method
/// calls <see cref="BeginWrite"/> and executes synchronously.
/// </remarks>
/// <example>
/// <code>
/// using (var trans = await realm.BeginWriteAsync())
/// {
/// realm.Add(new Dog
/// {
/// Name = "Rex"
/// });
/// await trans.CommitAsync();
/// // or just
/// // trans.Commit();
/// }
/// </code>
/// </example>
/// <param name="cancellationToken">
/// Optional cancellation token to stop waiting to start a write transaction.
/// </param>
/// <returns>An awaitable <see cref="Task"/> that returns a transaction in write mode.
/// A transaction is required for any creation, deletion or modification of objects persisted in a <see cref="Realm"/>.</returns>
public async Task<Transaction> BeginWriteAsync(CancellationToken cancellationToken = default)
{
ThrowIfDisposed();
ThrowIfFrozen("Starting a write transaction on a frozen Realm is not allowed.");
if (!AsyncHelper.TryGetValidContext(out var synchronizationContext))
{
return BeginWrite();
}
await SharedRealmHandle.BeginTransactionAsync(synchronizationContext, cancellationToken);
Debug.Assert(_activeTransaction is null, "There should be no active transaction");
return _activeTransaction = new Transaction(this);
}
/// <summary>
/// Execute an action inside a temporary <see cref="Transaction"/>. If no exception is thrown, the <see cref="Transaction"/> will be committed.
/// <b>If</b> the method is not called from a thread with a <see cref="SynchronizationContext"/> (like the UI thread), it behaves synchronously.
/// </summary>
/// <example>
/// <code>
/// await realm.WriteAsync(() =>
/// {
/// realm.Add(new Dog
/// {
/// Breed = "Dalmatian",
/// });
/// });
/// </code>
/// </example>
/// <param name="action">
/// Action to execute inside a <see cref="Transaction"/>, creating, updating, or removing objects.
/// </param>
/// <param name="cancellationToken">
/// Optional cancellation token to stop waiting to start a write transaction.
/// </param>
/// <returns>An awaitable <see cref="Task"/> that indicates that the transaction has been committed successfully.</returns>
public Task WriteAsync(Action action, CancellationToken cancellationToken = default)
{
ThrowIfDisposed();
Argument.NotNull(action, nameof(action));
return WriteAsync(() =>
{
action();
return true;
}, cancellationToken);
}
/// <summary>
/// Execute a delegate inside a temporary <see cref="Transaction"/>. If no exception is thrown, the <see cref="Transaction"/> will be committed.
/// <b>If</b> the method is not called from a thread with a <see cref="SynchronizationContext"/> (like the UI thread), it behaves synchronously.
/// </summary>
/// <example>
/// <code>
/// var dog = await realm.WriteAsync(() =>
/// {
/// return realm.Add(new Dog
/// {
/// Breed = "Dalmatian",
/// });
/// });
/// </code>
/// </example>
/// <param name="function">
/// Delegate with one return value to execute inside a <see cref="Transaction"/>, creating, updating, or removing objects.
/// </param>
/// <param name="cancellationToken">
/// Optional cancellation token to stop waiting to start a write transaction.
/// </param>
/// <typeparam name="T">The type returned by the input delegate.</typeparam>
/// <returns>
/// An awaitable <see cref="Task"/> that indicates that the transaction has been committed successfully. The result of
/// the task is the result returned by invoking <paramref name="function"/>.
/// </returns>
public async Task<T> WriteAsync<T>(Func<T> function, CancellationToken cancellationToken = default)
{
ThrowIfDisposed();
Argument.NotNull(function, nameof(function));
// If running on background thread, execute synchronously.
if (!AsyncHelper.TryGetValidContext(out _))
{
return Write(function);
}
using var transaction = await BeginWriteAsync(cancellationToken);
var result = function();
if (cancellationToken.IsCancellationRequested)
{
throw new TaskCanceledException();
}
await transaction.CommitAsync(CancellationToken.None);
return result;
}
/// <summary>
/// Update the <see cref="Realm"/> instance and outstanding objects to point to the most recent persisted version.
/// </summary>
/// <returns>
/// Whether the <see cref="Realm"/> had any updates. Note that this may return true even if no data has actually changed.
/// </returns>
public bool Refresh()
{
ThrowIfDisposed();
return SharedRealmHandle.Refresh();
}
/// <summary>
/// Asynchronously wait for the <see cref="Realm"/> instance and outstanding objects to get updated
/// to point to the most recent persisted version.
/// </summary>
/// <remarks>
/// On worker threads (where the SynchronizationContext) is null, this will call the blocking <see cref="Refresh"/>
/// method instead. On the main thread (or other threads that have SynchronizationContext), this will wait until
/// the instance automatically updates to resolve the task. Note that you must keep a reference to the Realm
/// until the returned task is resolved.
/// </remarks>
/// <returns>
/// Whether the <see cref="Realm"/> had any updates. Note that this may return true even if no data has actually changed.
/// </returns>
public Task<bool> RefreshAsync()
{
ThrowIfDisposed();
if (!AsyncHelper.TryGetValidContext(out _))
{
return Task.FromResult(Refresh());
}
return SharedRealmHandle.RefreshAsync();
}
/// <summary>
/// Extract an iterable set of objects for direct use or further query.
/// </summary>
/// <typeparam name="T">The Type T must be an <see cref="IRealmObject"/>.</typeparam>
/// <returns>A queryable collection that without further filtering, allows iterating all objects of class T, in this <see cref="Realm"/>.</returns>
/// <remarks>