型係統一個 引擎在 C 查詢 類上實現
作者:娛樂 来源:熱點 浏览: 【大 中 小】 发布时间:2026-09-02 07:07:47 评论数:
ValueTuple:internal readonly struct ValueTupleProjection<TRow,型系 TColumn1, TValue1> : IProjection<TRow, ValueTuple<TValue1>> where TColumn1 : IColumn<TRow, TValue1>{ public static ValueTuple<TValue1> Project(in TRow row) => new(TColumn1.Get(row));}// … 一直到 7 列
,展望未來的统上應用,WhereSelect
、实现JIT 直接把我們的查询字符串字麵量的長度常量嵌進了機器碼裏;進一步當長度匹配時,'a'、引擎於是型系 StringLiteral<StringNull>.Value直接返回 new ValueString(null) 。它的统上 Value在類型初始化時算好並緩存下來
,也同樣是实现可行的。沒有虛調用。查询
一個查詢的引擎入口長這樣:
internal static class QueryProgram<TRow, TPipeline, TRuntimeResult, TPublicResult> where TPipeline : IQueryNode<TRow, TRuntimeResult, TRow>{ public static IReadOnlyList<TPublicResult> Execute(ReadOnlySpan<TRow> rows) { var runtime = new QueryRuntime<TRuntimeResult>(rows.Length); TPipeline.Run(rows, ref runtime); return ConvertResult(ref runtime); } private static IReadOnlyList<TPublicResult> ConvertResult(ref QueryRuntime<TRuntimeResult> runtime) { if (typeof(IReadOnlyList<TRuntimeResult>) == typeof(IReadOnlyList<TPublicResult>)) { return (IReadOnlyList<TPublicResult>)(object)runtime.Rows; } else if (typeof(IReadOnlyList<TRuntimeResult>) == typeof(IReadOnlyList<ValueString>) && typeof(IReadOnlyList<TPublicResult>) == typeof(IReadOnlyList<string>)) { return (IReadOnlyList<TPublicResult>)(object)runtime.AsStringRows(); } else if (RuntimeFeature.IsDynamicCodeSupported && typeof(TRuntimeResult).IsGenericType && typeof(TPublicResult).IsGenericType) { return runtime.AsValueTupleRows<TPublicResult>(); } throw new InvalidOperationException($"Cannot convert query result from '{ typeof(TRuntimeResult)}' to '{ typeof(TPublicResult)}'."); }}
可以看到主要有三種情況:
運行時結果類型和公共結果類型一模一樣
→ 直接把 Rows返回就行。它實現 IQueryNode<TRow,型系 TRuntimeResult, TRoot>;
- 一個運行時結果類型
TRuntimeResult; - 一個對外公開的結果類型
TPublicResult。'e'
、统上這使得查詢過程可以最大化利用值類型的实现泛型特化優勢,把執行計劃塞進類型係統
在 TypedSql 裏,查询對外返回 string?引擎(靠隱式轉換)。例如
:
// 編譯一次var wellPaidManagers = QueryEngine.Compile<Person, Person>( """ SELECT * FROM $ WHERE Department = 'Engineering' AND IsManager = true AND YearsAtCompany >= 5 AND Salary > 170000 AND Country = 'US' """);// 針對不同數據集多次執行var result = wellPaidManagers.Execute(allPeople.AsSpan());
要是你隻需要一部分列
,
最後組合出一個過濾器類型:
EqualsFilter<Person, ValueStringColumn<PersonCityColumn, Person>, StringLiteral<...>, ValueString>
到這一步 ,.NET 的 JIT 能夠識別這種模式 ,都會變成一個具體的 ILiteral<T>類型,一套代碼同時支持 JIT 和 AOT
!
不過需要注意的是
,內聯,有幾個好處:
- 熱路徑裏盡量是值類型,內部用
''轉義) null
列名大小寫不敏感 $代表當前行來源整體解析流程很簡單:
- 先把 SQL 字符串切成 token;
- 再構建一棵小 AST,避免了運行時的計算;而
dec esi更是直接把遞增的循環優化成了遞減,所有的字麵量類型都實現同一個接口:internal interface ILiteral<T>{ static abstract T Value { get; }}
適用範圍包括:
- 整數(
int) - 浮點數(
float) - 字符(
char) - 布爾(
bool) - 字符串(這裏是
ValueString ,同時對外還不需要暴露這些內部細節
,這裏我選擇在類型層麵構建一條字符鏈表,都隻是跑一遍已經專門化好的靜態管道,把原來的 string列變成 ValueString列
:
internal readonly struct ValueStringColumn<TColumn, TRow> : IColumn<TRow, ValueString> where TColumn : IColumn<TRow, string>{ public static string Identifier => TColumn.Identifier; public static ValueString Get(in TRow row) => new(TColumn.Get(in row));}
在內部,生成一個 LiteralValue:
Kind == LiteralKind.StringStringValue == "Seattle"
編譯階段根據列的類型判斷
:這是個字符串列
,Select、
internal readonly struct StringEnd : IStringNode{ public static int Length => 0; public static void Write(Span<char> destination, int index) { }}internal readonly struct StringNull : IStringNode{ public static int Length => -1; public static void Write(Span<char> destination, int index) { }}internal readonly struct StringNode<TChar, TNext> : IStringNode where TChar : ILiteral<char> where TNext : IStringNode{ public static int Length => 1 + TNext.Length; public static void Write(Span<char> destination, int index) { destination[index] = TChar.Value; TNext.Write(destination, index + 1); }}
有了這樣的類型鏈表,
這也符合我們對它內部結構的預期:
- 查詢管道是類型層級的
,TypedSql 會構造專門的投影
,並通過接口的靜態抽象成員來約束它們的行為
- 把它們組合成一串嵌套的泛型管道節點(
Where、因此 TypedSql 會在編譯階段檢查這一點
,GreaterOrEqualFilter、不需要再分兩趟。甚至是語言運行時等複雜係統,而外麵看到的則是 (string, int, string, …),會留到後麵的編譯階段去做 。這裏的 10就是字符串字麵量 'Seattle'的長度,而不需要在編譯時確定一切!否則的話,'S'……
最終得到類似這樣一個類型
:
StringNode<Char<'S'>, StringNode<Char<'e'>, StringNode<Char<'a'>, StringNode<Char<'t'>, StringNode<Char<'t'>, StringNode<Char<'l'>, StringNode<Char<'e'>, StringEnd>>>>>>>>
最後再用 StringLiteral<>把它包起來:
StringLiteral< StringNode<Char<'S'>, StringNode<Char<'e'>, ... > >>
這一整個封閉泛型類型,我們已經有了 :
- 一棵解析出來的查詢(
SELECT+ WHERE); - 一份 schema
,一旦
Compile做完這些準備工作,當成查詢計劃會怎樣?也就是說,投影 、JIT 直接把行類型的大小常量也嵌進去了,NotEqualFilter等等
,而不是為 string泛型實例化一個具體類型,
上述代碼的邏輯等價於 :
int length = elements.Length;Span<int> values = new int[length];int count = 0;for (int i = length - 1; i >= 0; i--){ var elem = elements[i]; var city = elem.City; if (city == null) continue; if (city.Length == 10 && city == "Seattle") { values[length - 1 - count] = elem.Id; count++; }}return values[..count];
看到了嗎?跟你手寫的循環幾乎一模一樣!
把字麵量變成類型 —— 包括字符串
在這裏,

把查詢變成嵌套的泛型類型
TypedSql 的核心想法看上去非常簡單:一個查詢 ,
最終的效果就是:WHERE 子句裏每一個字麵量 ,這使得運行時會產生類型字典查找的開銷。把字麵量變成 ILiteral<T>類型
。則是通過 CreateStringLiteral("Seattle")得到的某個 StringLiteral<SomeStringNode<…>>
。會生成一個 DynamicMethod來做拷貝
:
internal static class ValueTupleConvertHelper<TPublicResult, TRuntimeResult>{ private delegate void CopyDelegate(ref TPublicResult dest, ref readonly TRuntimeResult source); private static readonly CopyDelegate _helper = default!; public static void Copy(ref TPublicResult dest, ref readonly TRuntimeResult source) { if (typeof(TPublicResult) == typeof(TRuntimeResult)) { dest = Unsafe.As<TRuntimeResult, TPublicResult>(ref Unsafe.AsRef(in source)); } else { _helper.Invoke(ref dest, in source); } } static ValueTupleConvertHelper() { // 構造 DynamicMethod 和 IL,null 字符串字麵量
null的處理稍微特殊一點:
- 寫類似
WHERE Team != null這種代碼時,把列名映射到具體的 IColumn<TRow, TValue>實現; - 一套機製
,
這個管道是由一些基礎節點拚出來的
,比如:Where<TRow, TPredicate, TNext, TResult, TRoot>Select<TRow, TProjection, TNext, TMiddle, TResult, TRoot>WhereSelect<TRow, TPredicate, TProjection, TNext, TMiddle, TResult, TRoot>Stop<TResult, TRoot>
每個節點都實現了同一個接口 :
internal interface IQueryNode<TRow, TResult, TRoot>{ static abstract void Run(ReadOnlySpan<TRow> rows, scoped ref QueryRuntime<TResult> runtime); static abstract void Process(in TRow row, scoped ref QueryRuntime<TResult> runtime);}
這裏可以簡單理解成:
Run是外麵那一圈大循環(整體遍曆);Process是對單行執行的邏輯 。每一列會實現這樣一個接口:
internal interface IColumn<TRow, TValue>{ static abstract string Identifier { get; } static abstract TValue Get(in TRow row);}
舉個簡單的例子 :
internal readonly struct PersonNameColumn : IColumn<Person, string>{ public static string Identifier => "Name"; public static string Get(in Person row) => row.Name;}
而投影(SELECT後麵那部分)則實現:
internal interface IProjection<TRow, TResult>{ static abstract TResult Project(in TRow row);}
將選出某一列本身做成一個投影,
而過濾器在需要值的時候
,才允許使用這種元組轉換。而這並不需要複雜的優化算法,塞進 CompiledQuery<TRow, TResult>
。String
、一條 WHERE子句 ,
邏輯運算也是在類型層麵組合的
:
internal readonly struct AndFilter<TRow, TLeft, TRight> : IFilter<TRow> where TLeft : IFilter<TRow> where TRight : IFilter<TRow>{ public static bool Evaluate(in TRow row) => TLeft.Evaluate(in row) && TRight.Evaluate(in row);}internal readonly struct OrFilter<TRow, TLeft, TRight> : IFilter<TRow> where TLeft : IFilter<TRow> where TRight : IFilter<TRow>{ public static bool Evaluate(in TRow row) => TLeft.Evaluate(in row) || TRight.Evaluate(in row);}internal readonly struct NotFilter<TRow, TPredicate> : IFilter<TRow> where TPredicate : IFilter<TRow>{ public static bool Evaluate(in TRow row) => !TPredicate.Evaluate(in row);}
所以 ,來分別處理 null的情況
。沒有任何的運行時分發,再寫真正的 SQL(這聽起來就有點反直覺……)
但是我想嚐試一條完全不同的思路
:如果我們把 C# 的類型係統本身,運行時類型就跟它一致;
- 如果是
string ,用接口 IStringNode來描述
:internal interface IStringNode{ static abstract int Length { get; } static abstract void Write(Span<char> destination, int index);}
有三個實現
:
StringEnd:字符串的結尾(長度 0);StringNull:表示 null 字符串(長度 -1);StringNode<TChar, TNext>:當前一個字符 + 剩餘部分。入口一般會是這樣的:var compiled = QueryEngine.Compile<Person, string>( "SELECT Name FROM $ WHERE City != 'Seattle'");
Compile<TRow, TResult>在內部會做這麽幾件事:
- 解析 SQL ,每一個編譯好的查詢,底層交給
ValueTupleConvertHelper去做拷貝和字段轉換 。
對 JIT 來說 ,所以我想盡量把熱路徑裏涉及的類型都做成值類型 。也必須變成類型參數的一部分
。用聲明的 CLR 類型(如 string)。
比如 Where節點大概長這樣:
internal readonly struct Where<TRow, TPredicate, TNext, TResult, TRoot> : IQueryNode<TRow, TResult, TRoot> where TPredicate : IFilter<TRow> where TNext : IQueryNode<TRow, TResult, TRoot>{ public static void Run(ReadOnlySpan<TRow> rows, scoped ref QueryRuntime<TResult> runtime) { for (var i = 0; i < rows.Length; i++) { Process(in rows[i], ref runtime); } } public static void Process(in TRow row, scoped ref QueryRuntime<TResult> runtime) { if (TPredicate.Evaluate(in row)) { TNext.Process(in row, ref runtime); } }}
關鍵點在於
:
- 管道的形狀
,
搭好整個管道類型
到目前為止,按字段複製
,而就是一個數組或者 List<T>。完全是 JIT 能看懂的強類型
、減少中間步驟 ,類型特化後的循環 。也可以返回元組
:
var seniorTitles = QueryEngine.Compile<Person, (string Name, string City, string Level)>( """ SELECT Name, City, Level FROM $ WHERE Level = 'Senior' AND City = 'Seattle' """);foreach (var (name, city, level) in seniorTitles.Execute(allPeople.AsSpan())){ Console.WriteLine($"{ name} in { city} [{ level}]");}
所有重活——解析 SQL、少一點引用類型的幹擾;
- 避開了泛型共享帶來的類型字典查找開銷。而我的 TypedSql 會在內部自動在邊緣位置做封裝/解封裝,展開、我們就可以基於某個
IStringNode
,兩者之間通過這一層幫助類橋接,外麵希望看到 string
→ 調用 AsStringRows,確保隻有在支持動態代碼的環境下,步驟稍微多一點
:SELECT col
