using System.Data;
using Microsoft.Data.SqlClient.Server;
using ZB.MOM.WW.OtOpcUa.Driver.Historian.Sql.Common;
namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.SqlServer;
///
/// The SqlDataRecord TVP builders. The HistorianValue ⇄ column mapping itself is
/// (shared with the other SQL backends).
///
internal static class SampleRowMapper
{
private static readonly SqlMetaData[] SampleMeta =
[
new("SourceTimeUtc", SqlDbType.DateTime2, 0, 7),
new("ValueKind", SqlDbType.TinyInt),
new("NumValue", SqlDbType.Float),
new("IntValue", SqlDbType.BigInt),
new("StrValue", SqlDbType.NVarChar, SqlMetaData.Max),
new("StatusCode", SqlDbType.Int),
];
private static readonly SqlMetaData[] TimeMeta = [new("T", SqlDbType.DateTime2, 0, 7)];
/// Builds SampleRow TVP records (datetime2(7); never a DataTable). Lazy; enumerate once.
/// Samples; must be time-unique (the TVP has a PK on time) and non-empty when bound.
/// Records for .
public static IEnumerable ToSampleRecords(IEnumerable rows)
{
foreach (var r in rows)
{
var c = SampleColumnMapper.ToColumns(r.Value);
var rec = new SqlDataRecord(SampleMeta);
rec.SetDateTime(0, DateTime.SpecifyKind(r.TimeUtc, DateTimeKind.Utc));
rec.SetByte(1, c.ValueKind);
if (c.NumValue is { } n) rec.SetDouble(2, n); else rec.SetDBNull(2);
if (c.IntValue is { } i) rec.SetInt64(3, i); else rec.SetDBNull(3);
if (c.StrValue is { } s) rec.SetString(4, s); else rec.SetDBNull(4);
rec.SetInt32(5, SampleColumnMapper.ToDbStatus(r.StatusCode));
yield return rec;
}
}
/// Builds TimeRow TVP records (datetime2(7)). Lazy; enumerate once.
/// Distinct UTC times; non-empty when bound.
/// Records for .
public static IEnumerable ToTimeRecords(IEnumerable timesUtc)
{
foreach (var t in timesUtc)
{
var rec = new SqlDataRecord(TimeMeta);
rec.SetDateTime(0, DateTime.SpecifyKind(t, DateTimeKind.Utc));
yield return rec;
}
}
}