94 lines
3.2 KiB
C#
94 lines
3.2 KiB
C#
#nullable enable
|
|
namespace bts.BlueOrb;
|
|
|
|
using BCG;
|
|
|
|
using Bts.DataStream;
|
|
using Bts.DataStreamCore;
|
|
|
|
using Spark.Core.Disposables;
|
|
|
|
using System;
|
|
|
|
public class ApplyStream : ViewStream {
|
|
readonly ViewStream source;
|
|
readonly Func<IBlueRow, object?> apply;
|
|
IBlueTableSchema? outputSchema;
|
|
BlueTableImmutable? lastFired;
|
|
IDisposable? sub;
|
|
|
|
public ApplyStream(ViewStream source, IFunctionEvaluator applyEvaluator) {
|
|
this.source = source;
|
|
apply = Apply;
|
|
|
|
object? Apply(IBlueRow r) {
|
|
var res = applyEvaluator.Evaluate(string.Empty, new (string?, int?, object?)[] { (null, 0, r) });
|
|
return res;
|
|
}
|
|
}
|
|
|
|
public ApplyStream(ViewStream source, Func<IBlueRow, object?> apply) {
|
|
this.source = source;
|
|
this.apply = apply;
|
|
}
|
|
|
|
protected override void myOnFirstSubscriber() {
|
|
sub = source.Subscribe(OnSourceChanged);
|
|
|
|
void OnSourceChanged(IDataPacket dp) {
|
|
Lazy<BlueTableImmutable> lastFired = new(() => this.lastFired ??= new(Log.notnull(outputSchema)));
|
|
Lazy<BlueTableImmutable.DataPacketBuilder> bd = new(() => lastFired.Value.ToDataPacketBuilder());
|
|
|
|
foreach (var r in dp.deletedRows) {
|
|
var res = apply(r);
|
|
if (res is IBlueRow blueRow) {
|
|
bd.Value.Remove(blueRow.Id());
|
|
} else if (res is IBlueRowCollection blueRows) {
|
|
foreach (var br in blueRows) {
|
|
bd.Value.Remove(br.Id());
|
|
}
|
|
} else {
|
|
Log.assert(false, $"apply delegate returned obj of unexpected type '{res?.GetType()}'");
|
|
}
|
|
}
|
|
foreach (var r in dp.addedRows) {
|
|
var res = apply(r);
|
|
if (res is IBlueRow blueRow) {
|
|
outputSchema ??= blueRow.schema;
|
|
bd.Value.AddOrUpdate(blueRow);
|
|
} else if (res is IBlueRowCollection blueRows) {
|
|
outputSchema ??= blueRows.schema;
|
|
foreach (var br in blueRows) {
|
|
bd.Value.AddOrUpdate(br);
|
|
}
|
|
} else {
|
|
if (outputSchema is null) {
|
|
// We get the outputSchema from the result of the first apply, if it's null, we
|
|
// cannot determine the output data type.
|
|
// TODO: maybe support specifying return type in DSL?
|
|
Log.notnull(res);
|
|
}
|
|
var resType = res?.GetType();
|
|
if (outputSchema is null) {
|
|
Log.notnull(resType);
|
|
Log.assert(ColumnInfo.isAllowedType(resType));
|
|
outputSchema = new BlueTableSchema(new ColumnInfo[] {
|
|
new("id", 0, typeof(int)),
|
|
new("result", 1, resType),
|
|
}, dp.newRows.schema.tableName + "_Apply");
|
|
}
|
|
bd.Value.AddOrUpdate(new BlueRow(outputSchema, new object?[] { r.Id(), res }));
|
|
// Log.assert(false, $"apply delegate returned obj of unexpected type '{res?.GetType()}'");
|
|
}
|
|
}
|
|
if (bd.IsValueCreated) {
|
|
myFireEvent(bd.Value.ToDataPacket(out this.lastFired));
|
|
}
|
|
}
|
|
}
|
|
|
|
protected override void myOnLastSubscriber() {
|
|
Disposable.dispose(ref sub);
|
|
}
|
|
}
|