Beispiel #1
0
 /// <summary>
 /// Strictly for testing
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="@event"></param>
 /// <returns></returns>
 public EventStream Add <T>(T @event)
 {
     _events.Add(new Event <T>(@event)
     {
         Id = CombGuidIdGeneration.NewGuid()
     });
     return(this);
 }
Beispiel #2
0
        public static Guid GenerateNewGuid(bool standardGuid)
        {
            Guid resultGuid = standardGuid
                ? Guid.NewGuid()
                : CombGuidIdGeneration.NewGuid();

            return(resultGuid);
        }
Beispiel #3
0
        public EventStream AddEvents(IEnumerable <IEvent> events)
        {
            _events.AddRange(events);
            _events.Where(x => x.Id == Guid.Empty).Each(x => x.Id = CombGuidIdGeneration.NewGuid());

            _events.Each(x => x.StreamId = Id);

            return(this);
        }
Beispiel #4
0
 /// <summary>
 /// Strictly for testing
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="@event"></param>
 /// <returns></returns>
 public StreamAction Add <T>(T @event)
 {
     _events.Add(new Event <T>(@event)
     {
         Id        = CombGuidIdGeneration.NewGuid(),
         StreamId  = Id,
         StreamKey = Key,
     });
     return(this);
 }
Beispiel #5
0
        public void AddParameters(IBatchCommand batch)
        {
            var patchJson    = batch.Serializer.ToCleanJson(_patch);
            var patchParam   = batch.AddParameter(patchJson, NpgsqlDbType.Jsonb);
            var versionParam = batch.AddParameter(CombGuidIdGeneration.NewGuid(), NpgsqlDbType.Uuid);

            var where = _fragment.ToSql(batch.Command);

            _sql = $@"
update {_document.Table.QualifiedName} as d 
set data = {_transform.Function.QualifiedName}(data, :{patchParam.ParameterName}), {DocumentMapping.LastModifiedColumn} = (now() at time zone 'utc'), {DocumentMapping.VersionColumn} = :{versionParam.ParameterName}
where {where}";
        }
Beispiel #6
0
        public void ConfigureCommand(CommandBuilder builder, IMartenSession session)
        {
            var patchParam = builder.AddJsonParameter(_serializer.ToCleanJson(_patch));

            if (_patch.TryGetValue("value", out var document))
            {
                var value = PossiblyPolymorhpic ? _serializer.ToJsonWithTypes(document) : _serializer.ToJson(document);
                var copy  = new Dictionary <string, object>();
                foreach (var item in _patch)
                {
                    copy.Add(item.Key, item.Value);
                }
                copy["value"] = VALUE_LOOKUP;

                var patchJson     = _serializer.ToJson(copy);
                var replacedValue = patchJson.Replace($"\"{VALUE_LOOKUP}\"", value);

                patchParam = builder.AddJsonParameter(replacedValue);
            }

            var versionParam = builder.AddParameter(CombGuidIdGeneration.NewGuid(), NpgsqlDbType.Uuid);

            builder.Append("update ");
            builder.Append(_storage.TableName.QualifiedName);
            builder.Append(" as d set data = ");
            builder.Append(_transform.Identifier.QualifiedName);
            builder.Append("(data, :");
            builder.Append(patchParam.ParameterName);
            builder.Append("), ");
            builder.Append(SchemaConstants.LastModifiedColumn);
            builder.Append(" = (now() at time zone 'utc'), ");
            builder.Append(SchemaConstants.VersionColumn);
            builder.Append(" = :");
            builder.Append(versionParam.ParameterName);

            if (!_fragment.Contains("where"))
            {
                builder.Append(" where ");
            }
            else
            {
                builder.Append(" ");
            }

            _fragment.Apply(builder);

            applyUpdates(builder, _fragment);
        }
        public void Apply(CommandBuilder sql)
        {
            var version = CombGuidIdGeneration.NewGuid();

            sql.Append("update ");
            sql.Append(_storage.TableName.QualifiedName);
            sql.Append(" as d set data = ");
            sql.Append(_function.Identifier.QualifiedName);
            sql.Append("(data), ");
            sql.Append(SchemaConstants.LastModifiedColumn);
            sql.Append(" = (now() at time zone 'utc'), ");
            sql.Append(SchemaConstants.VersionColumn);
            sql.Append(" = '");
            sql.Append(version.ToString());
            sql.Append("'");
        }
Beispiel #8
0
        public void Apply(CommandBuilder sql)
        {
            var version = CombGuidIdGeneration.NewGuid();

            sql.Append("update ");
            sql.Append(_mapping.Table.QualifiedName);
            sql.Append(" as d set data = ");
            sql.Append(_function.Identifier.QualifiedName);
            sql.Append("(data), ");
            sql.Append(DocumentMapping.LastModifiedColumn);
            sql.Append(" = (now() at time zone 'utc'), ");
            sql.Append(DocumentMapping.VersionColumn);
            sql.Append(" = '");
            sql.Append(version);
            sql.Append("'");
        }
Beispiel #9
0
        private static void writeBasicSql(CommandBuilder sql, IDocumentMapping mapping, TransformFunction transform)
        {
            var version = CombGuidIdGeneration.NewGuid();

            sql.Append("update ");
            sql.Append(mapping.Table.QualifiedName);
            sql.Append(" as d set data = ");
            sql.Append(transform.Identifier.QualifiedName);
            sql.Append("(data), ");
            sql.Append(DocumentMapping.LastModifiedColumn);
            sql.Append(" = (now() at time zone 'utc'), ");
            sql.Append(DocumentMapping.VersionColumn);
            sql.Append(" = '");
            sql.Append(version);
            sql.Append("'");
        }
Beispiel #10
0
        public StreamAction AddEvents(IEnumerable <object> events)
        {
            // TODO -- let's get rid of this maybe?
            _events.AddRange(events.Select(coerce));

            foreach (var @event in _events)
            {
                if (@event.Id == Guid.Empty)
                {
                    @event.Id = CombGuidIdGeneration.NewGuid();
                }
                @event.StreamId  = Id;
                @event.StreamKey = Key;
            }

            return(this);
        }
Beispiel #11
0
        internal StreamAction AddEvents(IReadOnlyList <IEvent> events)
        {
            // TODO -- let's get rid of this maybe?
            _events.AddRange(events);

            foreach (var @event in events)
            {
                if (@event.Id == Guid.Empty)
                {
                    @event.Id = CombGuidIdGeneration.NewGuid();
                }
                @event.StreamId  = Id;
                @event.StreamKey = Key;
            }

            return(this);
        }
Beispiel #12
0
        public void PrepareEvents(int currentVersion, EventGraph graph, Queue <long> sequences, IMartenSession session)
        {
            var timestamp = DateTimeOffset.UtcNow;

            if (AggregateType != null)
            {
                AggregateTypeName = graph.AggregateAliasFor(AggregateType);
            }

            var i = currentVersion;

            if (currentVersion != 0)
            {
                // Guard logic for optimistic concurrency
                if (ExpectedVersionOnServer.HasValue)
                {
                    if (currentVersion != ExpectedVersionOnServer.Value)
                    {
                        throw new EventStreamUnexpectedMaxEventIdException((object)Key ?? Id, AggregateType, ExpectedVersionOnServer.Value, currentVersion);
                    }
                }

                ExpectedVersionOnServer = currentVersion;
            }



            foreach (var @event in _events)
            {
                @event.Version        = ++i;
                @event.DotNetTypeName = graph.DotnetTypeNameFor(@event.EventType);

                var mapping = graph.EventMappingFor(@event.EventType);
                @event.EventTypeName = mapping.EventTypeName;
                if (@event.Id == Guid.Empty)
                {
                    @event.Id = CombGuidIdGeneration.NewGuid();
                }
                @event.Sequence = sequences.Dequeue();
                @event.TenantId ??= session.Tenant.TenantId;
                @event.Timestamp = timestamp;
            }

            Version = Events.Last().Version;
        }
        public void load_non_existing_with_a_store_shoudl_return_new_added_document()
        {
            var routeId = CombGuidIdGeneration.NewGuid();

            using (var session = theStore.OpenSession())
            {
                var details = session.Load <RouteDetails>(routeId);
                details.ShouldBeNull();

                var routeDetails = new RouteDetails {
                    Id = routeId
                };
                session.Store(routeDetails);

                details = session.Load <RouteDetails>(routeId);

                details.ShouldBeTheSameAs(routeDetails);
            }
        }
Beispiel #14
0
        public void RegisterUpdate(UpdateBatch batch, object entity, string json)
        {
            var newVersion     = CombGuidIdGeneration.NewGuid();
            var currentVersion = batch.Versions.Version <T>(Identity(entity));

            ICallback callback = null;

            if (_mapping.UseOptimisticConcurrency)
            {
                callback = new OptimisticConcurrencyCallback <T>(Identity(entity), batch.Versions, newVersion, currentVersion);
            }


            var call = batch.Sproc(_upsertName, callback);



            _sprocWriter(call, (T)entity, batch, _mapping, currentVersion, newVersion);
        }
Beispiel #15
0
        internal bool TryCreateTombstoneBatch(DocumentSessionBase session, out UpdateBatch batch)
        {
            if (session.UnitOfWork.Streams.Any())
            {
                var stream = StreamAction.ForTombstone();

                var tombstone = new Tombstone();
                var mapping   = EventMappingFor <Tombstone>();

                var operations = new List <IStorageOperation>();
                var storage    = session.EventStorage();

                var dotNetTypeName = DotnetTypeNameFor(typeof(Tombstone));

                operations.Add(_establishTombstone.Value);
                var tombstones = session.UnitOfWork.Streams
                                 .SelectMany(x => x.Events)
                                 .Select(x => new Event <Tombstone>(tombstone)
                {
                    Sequence       = x.Sequence,
                    Version        = x.Version,
                    TenantId       = x.TenantId,
                    StreamId       = EstablishTombstoneStream.StreamId,
                    StreamKey      = EstablishTombstoneStream.StreamKey,
                    Id             = CombGuidIdGeneration.NewGuid(),
                    EventTypeName  = mapping.EventTypeName,
                    DotNetTypeName = dotNetTypeName
                })
                                 .Select(e => storage.AppendEvent(this, session, stream, e));

                operations.AddRange(tombstones);

                batch = new UpdateBatch(operations);

                return(true);
            }

            batch = null;
            return(false);
        }
Beispiel #16
0
        public Envelope CloneForSending(Envelope envelope)
        {
            if (envelope.Message == null)
            {
                throw new ArgumentNullException(nameof(envelope.Message), "Envelope.Message cannot be null");
            }

            var sending = envelope.Clone();

            sending.Id         = CombGuidIdGeneration.NewGuid();
            sending.OriginalId = envelope.Id;

            sending.ReplyUri = envelope.ReplyUri ?? Subscriber.ReplyUri;

            sending.ContentType = envelope.ContentType ?? ContentType;

            sending.Writer      = Writer;
            sending.Destination = Destination;
            sending.Route       = this;

            return(sending);
        }
Beispiel #17
0
        public void RegisterUpdate(string tenantIdOverride, UpdateStyle updateStyle, UpdateBatch batch, object entity, string json)
        {
            var newVersion     = CombGuidIdGeneration.NewGuid();
            var currentVersion = batch.Versions.Version <T>(Identity(entity));

            // Set the current version
            _setVersion(entity.As <T>(), newVersion);

            ICallback           callback           = null;
            IExceptionTransform exceptionTransform = null;
            var sprocName = determineDbObjectName(updateStyle, batch);

            var tenantId = tenantIdOverride ?? batch.TenantId;

            if (_mapping.UseOptimisticConcurrency)
            {
                Action <Guid> setVersion = version => _setVersion(entity.As <T>(), version);

                callback = new OptimisticConcurrencyCallback <T>(batch.Concurrency, Identity(entity), batch.Versions, newVersion,
                                                                 currentVersion, setVersion);
            }



            if (!_mapping.UseOptimisticConcurrency && updateStyle == UpdateStyle.Update)
            {
                callback = new UpdateDocumentCallback <T>(Identity(entity));
            }

            if (updateStyle == UpdateStyle.Insert)
            {
                exceptionTransform = new InsertExceptionTransform <T>(Identity(entity), _mapping.Table.Name);
            }


            var call = batch.Sproc(sprocName, callback, exceptionTransform);

            _sprocWriter(call, (T)entity, batch, _mapping, currentVersion, newVersion, tenantId);
        }
Beispiel #18
0
 public StreamAction StartStream(params object[] events)
 {
     return(StartStream(CombGuidIdGeneration.NewGuid(), events));
 }
Beispiel #19
0
 public StreamAction StartStream(Type aggregateType, params object[] events)
 {
     return(StartStream(aggregateType, CombGuidIdGeneration.NewGuid(), events));
 }
Beispiel #20
0
 public Guid New() => CombGuidIdGeneration.NewGuid();
Beispiel #21
0
        private static string toBasicSql(IDocumentMapping mapping, TransformFunction transform)
        {
            var version = CombGuidIdGeneration.NewGuid();

            return($"update {mapping.Table.QualifiedName} as d set data = {transform.Function.QualifiedName}(data), {DocumentMapping.LastModifiedColumn} = (now() at time zone 'utc'), {DocumentMapping.VersionColumn} = '{version}'");
        }
Beispiel #22
0
 public EventStream StartStream <TAggregate>(params object[] events) where TAggregate : class
 {
     return(StartStream <TAggregate>(CombGuidIdGeneration.NewGuid(), events));
 }
Beispiel #23
0
 protected void setVersionParameter(NpgsqlParameter parameter)
 {
     _version = CombGuidIdGeneration.NewGuid();
     parameter.NpgsqlDbType = NpgsqlDbType.Uuid;
     parameter.Value        = _version;
 }