Path: redb/redb.Core/Providers/Base/ObjectStorageProviderBase.AddNewObjects.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Providers/Base/ObjectStorageProviderBase.AddNewObjects.cs ---- using redb.Core.Providers; using redb.Core.Data; using redb.Core.Utils; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Models.Configuration; using redb.Core.Models.Security; using redb.Core.Query; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System; namespace redb.Core.Providers.Base { /// /// BULK INSERT - high-performance creation of multiple objects /// public abstract partial class ObjectStorageProviderBase { /// /// BULK INSERT: Create multiple new objects in one operation (WITHOUT permission checks) /// The batch save's preparation steps + BulkInsert for maximum performance /// public async Task> AddNewObjectsAsync(IEnumerable> objects, CancellationToken cancellationToken = default) where TProps : class, new() { return await AddNewObjectsAsync(objects, _securityContext.CurrentUser, cancellationToken); } /// /// BULK INSERT with explicit user: Create multiple new objects (WITHOUT permission checks) /// public async Task> AddNewObjectsAsync(IEnumerable> objects, IRedbUser user, CancellationToken cancellationToken = default) where TProps : class, new() { // Materialize IEnumerable to list for multiple iterations var objectsList = objects?.ToList() ?? new List>(); if (objectsList.Count == 0) { return new List(); } // Validation foreach (var obj in objectsList) { if (obj.Props == null) { throw new ArgumentException($"Object properties '{obj.Name}' cannot be null", nameof(objects)); } } // Initial processing of hashes and schemes for main objects foreach (var obj in objectsList) { // Recalculate hash var currentHash = RedbHash.ComputeFor(obj); if (currentHash.HasValue) { obj.Hash = currentHash.Value; } // Auto-determination of scheme (WITHOUT checks for existing objects) if (obj.SchemeId == 0 && _configuration.AutoSyncSchemesOnSave) { var existingScheme = await _schemeSync.GetSchemeByTypeAsync(); if (existingScheme != null) { obj.SchemeId = existingScheme.Id; } else if (_configuration.AutoSyncSchemesOnSave) { try { var scheme = await _schemeSync.SyncSchemeAsync(); obj.SchemeId = scheme.Id; } catch (Exception ex) { throw; } } } } // === THE BATCH SAVE'S PREPARATION STEPS === var objectsToSave = new List(); var valuesToSave = new List(); var processedObjectIds = new HashSet(); var seenInstances = new HashSet(ReferenceEqualityComparer.Instance); // STEP 2: Recursive collection of all objects (main + nested IRedbObject) // References by id carry no hash yet: resolve them in one query, as the batch save does. Hashing before // that wrote "id:" for every reference, and the stored hash never matched the loaded one. var referenceStubs = new List(); foreach (var obj in objectsList) { await CollectAllObjectsRecursively(obj, objectsToSave, processedObjectIds, seenInstances, referenceStubs); } await ResolveReferenceHashesAsync(referenceStubs, cancellationToken); await EnsureNoHeldShapesAsync(objectsToSave, cancellationToken); // A referenced object that already carries an id may be one saved before, by the very instance that was // saved (its props loaded, so the collector takes it). The batch save tells such objects from new ones by // asking the database; the bulk insert inserted them again and failed on the primary key of _objects. A // saved one is a reference here: its referrer writes its id, its own row and values stay as they are. // The same statement reads the stored structure hash of every scheme the bulk insert writes (the save reads it // with its existing objects): a scheme another process changed since this one cached it is read again before // any value row is built, and a class older than the scheme's version is refused. One statement per call, // before anything is written. await EnsureSchemesForAllTypes(objectsToSave, cancellationToken); var passedIn = new HashSet(objectsList, ReferenceEqualityComparer.Instance); var referencedIds = objectsToSave.Where(o => o.Id != 0 && !passedIn.Contains(o)).Select(o => o.Id).Distinct().ToArray(); var (savedRows, hashByScheme) = await SelectExistingAndSchemeHashesAsync(referencedIds, objectsToSave, cancellationToken); if (savedRows.Count > 0) { var saved = savedRows.Select(r => r.Id).ToHashSet(); objectsToSave.RemoveAll(o => !passedIn.Contains(o) && saved.Contains(o.Id)); } await RefreshStaleSchemesAsync(objectsToSave, hashByScheme, cancellationToken); // STEP 3: Assign IDs to all objects without ID (via GetNextKey) var created = objectsToSave.Where(o => o.Id == 0).ToList(); await AssignMissingIds(objectsToSave, user, cancellationToken); // A nested object keeps the ParentId it carries, as in SaveAsync: a reference is not a place in the tree. // The bulk insert used to put every nested new object under the first object it was given. // Hashes are final only once ids and parents are set: a parent hashes "id:hash" of every reference, and // an object created here was still id 0 above. Children before parents across the graph, as the batch // save does. RecomputeHashesPostOrder(objectsToSave); // STEP 5: Recursive processing of Props of all objects into values lists await ProcessAllObjectsPropertiesRecursively(objectsToSave, valuesToSave, cancellationToken: cancellationToken); // STEP 6: WITHOUT Delete strategy - these are NEW objects // STEP 7: BULK INSERT instead of regular saving // The object rows and the value rows go in as one unit: a failed value insert leaves no object behind. In a // caller transaction ExecuteAtomicAsync joins it, and the caller owns the rollback. try { await _context.ExecuteAtomicAsync(() => CommitAllChangesBulk(objectsToSave, valuesToSave, cancellationToken), cancellationToken); } catch (Exception ex) when (Data.DbErrorClassifier.IsUniqueViolation(ex)) { throw await TranslateUniqueViolationAsync(ex, objectsList.FirstOrDefault()?.SchemeId); } catch (Exception ex) when (IsStaleKeyCache(ex, created.Count > 0)) { throw StaleKeyCacheFailure(ex, created); } // Return IDs of all created main objects var resultIds = objectsList.Select(o => o.Id).ToList(); return resultIds; } /// /// Step 7 (BULK): Bulk save with BulkInsert instead of Add(). /// private async Task CommitAllChangesBulk(List objects, List valuesList, CancellationToken cancellationToken) { // 1. BULK INSERT objects if (objects.Count > 0) { var objectRecords = objects.Select(obj => { var record = new RedbObjectRow { Id = obj.Id, IdScheme = obj.SchemeId, IdParent = obj.ParentId, IdOwner = obj.OwnerId, IdWhoChange = obj.WhoChangeId, Name = obj.Name, Hash = obj.Hash, DateBegin = obj.DateBegin, DateComplete = obj.DateComplete, Key = obj.Key, ValueLong = obj.ValueLong, ValueString = obj.ValueString, ValueGuid = obj.ValueGuid, ValueBool = obj.ValueBool, ValueDouble = obj.ValueDouble, ValueNumeric = obj.ValueNumeric, ValueDatetime = obj.ValueDatetime, ValueBytes = obj.ValueBytes, Note = obj.Note }; if (_configuration.AutoSetModifyDate) { record.DateCreate = DateTimeOffset.UtcNow; record.DateModify = DateTimeOffset.UtcNow; } else { var dateCreate = obj.DateCreate; record.DateCreate = dateCreate == DateTimeOffset.MinValue ? DateTimeOffset.UtcNow : dateCreate; var dateModify = obj.DateModify; record.DateModify = dateModify == DateTimeOffset.MinValue ? DateTimeOffset.UtcNow : dateModify; } return record; }).ToList(); await _context.Bulk.BulkInsertObjectsAsync(objectRecords, cancellationToken); } // 2. BULK INSERT values (with topological sort for FK constraint) if (valuesList.Count > 0) { await AssignValueIdsAsync(valuesList, [], cancellationToken); var sortedValues = ValuesTopologicalSort.SortByFkDependency(valuesList); await _context.Bulk.BulkInsertValuesAsync(sortedValues, cancellationToken); } } } }