the first query moves off ef, and the aot edge reads its own policy from the database
ci / build, test, smoke (push) Failing after 3m33s
ci / the same smoke on an image with no base (push) Successful in 8m10s
ci / lint the workflow and the shell (push) Failing after 19s
ci / the operator page in a real browser (push) Successful in 4m41s
ci / build the image and smoke it (push) Failing after 8m11s
ci / build, test, smoke (push) Failing after 3m33s
ci / the same smoke on an image with no base (push) Successful in 8m10s
ci / lint the workflow and the shell (push) Failing after 19s
ci / the operator page in a real browser (push) Successful in 4m41s
ci / build the image and smoke it (push) Failing after 8m11s
Wall 3 starts. Two projects, one query path, measured. dotnet/OpenWaf.Data is the runtime: OrmContext (a DbDataSource plus an ISqlDialect), Query<T>, RowReader, OrmMeta. It is typed over System.Data.Common and carries no provider package; the driver is supplied at composition, which is how the neighbouring deployment ships it too. Query<T> renders SQL by walking the expression tree rather than compiling it — that is the exact difference from EF's pipeline, and the reason it survives a NativeAOT link where EF does not. The supported grammar is a closed set that refuses by name: joins, subqueries, aggregates other than COUNT, updates, deletes, JSON columns and method calls each raise UnsupportedQueryNodeException naming the node, because a renderer that guesses is a renderer that ships wrong SQL. dotnet/OpenWaf.Data.Generator is a Roslyn incremental generator attached to OpenWaf.Infrastructure as an analyzer. For a [Table] class it emits the column map, the row materializer and an OrmMeta.Register call inside a [ModuleInitializer], so the question a NativeAOT binary cannot answer — what are this type's properties — is never asked. The generated file is ordinary C#, readable in obj/ and asserted against. PolicySetting is the entity moved and EdgePolicyProvider.ReloadAsync the call site, which was the first refusal in the probe log. Program.cs composes the driver and dialect on the same Database:Provider switch EF uses, so one generated query serves sqlite (the shipped image) and PostgreSQL (the migrations' provider). EF still owns every write and every other read; the two layers coexist on one composition root, which is what makes this incremental rather than a rewrite. Measured on the AOT binary, same probe, same window, before and after: queries refused at run time 32 -> 18; EdgePolicyProvider reload failures 1 -> 0; native binary 49,609,680 -> 49,676,016 bytes. The 18 that remain are named by their own frames: 14 EdgeStateStore.RefreshAsync, 2 BlockStore.WriteBanAsync, 1 BlockStore.AddOperatorAsync, 1 admin endpoint. The sqlite timestamp column turned out to be a contract, not a detail. The model puts EF's DateTimeOffsetToBinaryConverter on every timestamp column, so every row already written says (localTicks / 1000) * 2048 + (offsetMinutes & 2047); the formula was derived by probing EF's converter and is now pinned by SqliteTimestampEncodingTests against that converter over five instants including +05:30, -05:00 and DateTimeOffset.MinValue — including the microsecond truncation the /1000 imposes, which is EF's behaviour and is now a test rather than a future surprise. Two build traps, both paid for and both recorded where the next person will hit them. -p:PublishAot on the command line is a global property, so it reaches every project in the graph including a netstandard2.0 Roslyn analyzer, and the publish dies with NETSDK1207; AOT is now switched by OpenWafAot=true, which only OpenWaf.Edge.csproj turns into PublishAot — the same shape as the existing OpenWafCompiledModel switch. And a raw Microsoft.Data.Sqlite data source needs SQLitePCL.Batteries.Init() before its first open, because the order in which EF's provider and this data source are first used is not guaranteed. Gates on this tree: build 0 warnings, unit 391/391 (13 new: rendered SQL for both dialects, null tests, the captured-null case, the refusals, the timestamp encoding), integration 408/408, smoke 256/256, and the AOT probe above. One earlier run of the 408 carried a single failure in AdminConsoleTests at a host load average near 30 and the next run was clean; recorded rather than hidden, in the same family as the load-sensitive compose gates this README already documents.
This commit is contained in:
@@ -58,9 +58,7 @@ RUN . /rid && dotnet publish OpenWaf.Edge/OpenWaf.Edge.csproj \
|
|||||||
-c Release \
|
-c Release \
|
||||||
-r "$RID" \
|
-r "$RID" \
|
||||||
--self-contained true \
|
--self-contained true \
|
||||||
-p:PublishAot=true \
|
-p:OpenWafAot=true \
|
||||||
-p:InvariantGlobalization=true \
|
|
||||||
-p:DebugType=none \
|
|
||||||
-p:OpenWafCompiledModel=true \
|
-p:OpenWafCompiledModel=true \
|
||||||
-p:NoWarn=IL2026%3BIL3050 \
|
-p:NoWarn=IL2026%3BIL3050 \
|
||||||
-p:IlcTreatWarningsAsErrors=false \
|
-p:IlcTreatWarningsAsErrors=false \
|
||||||
|
|||||||
@@ -416,9 +416,9 @@ bought; as of 2026-10-07 **the first of those two is down on this tree**:
|
|||||||
never missing code generation, only a registered contract for the shapes that
|
never missing code generation, only a registered contract for the shapes that
|
||||||
cross the wire. See the next section.
|
cross the wire. See the next section.
|
||||||
- every query is still refused — `Query wasn't precompiled and dynamic code isn't
|
- every query is still refused — `Query wasn't precompiled and dynamic code isn't
|
||||||
supported with NativeAOT`, **32 refusals in the 2026-10-07 probe window**
|
supported with NativeAOT`, **18 refusals in the 2026-10-07 probe window** —
|
||||||
(30 in the run before it — it counts a window, not a total, because the
|
32 before the first query moved off EF, and the count is a window rather than a
|
||||||
background refresh loop retries on its own clock) —
|
total because the background refresh loop retries on its own clock —
|
||||||
which is EF's precompiler (the NativeAOT entry in `docs/ARCHITECTURE.md`
|
which is EF's precompiler (the NativeAOT entry in `docs/ARCHITECTURE.md`
|
||||||
carries its four untranslatable query shapes and its codegen bug). This is the
|
carries its four untranslatable query shapes and its codegen bug). This is the
|
||||||
one wall left, and it is the generator slice.
|
one wall left, and it is the generator slice.
|
||||||
@@ -534,6 +534,74 @@ a `$"…{x}…"` was counted as code. The numbers above are the same tree re-mea
|
|||||||
with a scanner that skips strings, char literals and comments; the 111 that became
|
with a scanner that skips strings, char literals and comments; the 111 that became
|
||||||
`ErrorDto` is the one figure both scanners agree on.
|
`ErrorDto` is the one figure both scanners agree on.
|
||||||
|
|
||||||
|
### The first query that does not go through EF
|
||||||
|
|
||||||
|
The query wall is where the generator slice starts, and the first path is moved
|
||||||
|
and measured. Two new projects:
|
||||||
|
|
||||||
|
* **`dotnet/OpenWaf.Data`** — the runtime, typed over `System.Data.Common` with
|
||||||
|
no provider package in it. `OrmContext` carries a `DbDataSource` and an
|
||||||
|
`ISqlDialect`; `Query<T>` renders SQL by **walking** the expression tree, which
|
||||||
|
is the whole point: EF's pipeline compiles trees into IL at run time, and that
|
||||||
|
is the sentence the probe counts. The supported grammar is a closed set and it
|
||||||
|
says so — joins, subqueries, aggregates other than `COUNT`, updates, deletes,
|
||||||
|
JSON columns and method calls each throw `UnsupportedQueryNodeException` naming
|
||||||
|
the node, rather than rendering SQL that is quietly wrong.
|
||||||
|
* **`dotnet/OpenWaf.Data.Generator`** — a Roslyn incremental generator attached to
|
||||||
|
`OpenWaf.Infrastructure` as an analyzer. For a `[Table]` class it emits the
|
||||||
|
column map, the row materializer and an `OrmMeta.Register` call in a
|
||||||
|
`[ModuleInitializer]`. Nothing at run time asks a type what its properties are,
|
||||||
|
because the answer is a switch the compiler wrote.
|
||||||
|
|
||||||
|
`PolicySetting` is the first entity moved, `EdgePolicyProvider.ReloadAsync` the
|
||||||
|
first call site, and `Program.cs` composes the driver and dialect on the same
|
||||||
|
`Database:Provider` switch EF uses — sqlite for the shipped image, PostgreSQL for
|
||||||
|
the migrations' provider, one generated query serving both.
|
||||||
|
|
||||||
|
Measured on the AOT binary, same probe, same window, before and after:
|
||||||
|
|
||||||
|
```
|
||||||
|
queries refused at run time: 32 -> 18
|
||||||
|
policy reload failures: 1 -> 0
|
||||||
|
native binary bytes: 49,609,680 -> 49,676,016 (+66,336)
|
||||||
|
```
|
||||||
|
|
||||||
|
The 18 that remain are named by their own stack frames: **14** in
|
||||||
|
`EdgeStateStore.RefreshAsync`, **2** in `BlockStore.WriteBanAsync`, **1** in
|
||||||
|
`BlockStore.AddOperatorAsync`, **1** in an admin endpoint. The policy read — the
|
||||||
|
first refusal in the log before this change — is gone from that list.
|
||||||
|
|
||||||
|
Two facts about the storage contract came out of it. The model puts EF's
|
||||||
|
`DateTimeOffsetToBinaryConverter` on every timestamp column of sqlite, so that
|
||||||
|
encoding — `(localTicks / 1000) * 2048 + (offsetMinutes & 2047)` — is what every
|
||||||
|
row this application has written already says, and the dialect reproduces it.
|
||||||
|
`SqliteTimestampEncodingTests` asserts the reproduction equals EF's own converter
|
||||||
|
over five instants (a `+03:00`, a `-05:00`, the half-hour `+05:30`, a sub-second
|
||||||
|
value and `DateTimeOffset.MinValue`), and asserts the resolution too: the `/1000`
|
||||||
|
means a round trip through the column drops the sub-microsecond digits, which is
|
||||||
|
EF's behaviour and is now a test rather than a surprise.
|
||||||
|
|
||||||
|
Two build facts, both paid for:
|
||||||
|
|
||||||
|
* **`-p:PublishAot` on the command line is a global property**, so it reaches
|
||||||
|
every project in the graph — including a `netstandard2.0` Roslyn analyzer — and
|
||||||
|
the publish dies with `NETSDK1207: Ahead-of-time compilation is not supported
|
||||||
|
for the target framework`. AOT is now switched on by `OpenWafAot=true`, which
|
||||||
|
only `OpenWaf.Edge.csproj` acts on; the same pattern this tree already used for
|
||||||
|
`OpenWafCompiledModel`.
|
||||||
|
* **A raw `Microsoft.Data.Sqlite` data source needs the native bundle
|
||||||
|
registered**: `SQLitePCL.Batteries.Init()` before the first open, because the
|
||||||
|
order in which EF's provider and this data source are first used is not
|
||||||
|
guaranteed. (`SqliteConnectionFactory` is not public API; the factory is
|
||||||
|
`SqliteFactory.Instance.CreateDataSource(…)`.)
|
||||||
|
|
||||||
|
Gates on this tree: build **0 warnings**, unit **391/391** (13 new: the rendered
|
||||||
|
SQL for both dialects, the null tests, the captured-null case, the refusals, and
|
||||||
|
the timestamp encoding), integration **408/408**, smoke **256/256**. One run of
|
||||||
|
the 408 carried a single failure in `AdminConsoleTests` at a host load average of
|
||||||
|
about 30 and the next run was clean; recorded rather than hidden, and it is the
|
||||||
|
load-sensitive shape this README already documents for the compose gates.
|
||||||
|
|
||||||
## Schema
|
## Schema
|
||||||
|
|
||||||
Migrations are the schema of record for PostgreSQL, which is the provider a
|
Migrations are the schema of record for PostgreSQL, which is the provider a
|
||||||
|
|||||||
+40
-4
@@ -47,10 +47,10 @@ classifies the status, and is the only thing that can create an engine ban.
|
|||||||
starts, creates its own schema from the DDL the binary carries **and serves**:
|
starts, creates its own schema from the DDL the binary carries **and serves**:
|
||||||
`Now listening on:`, `/healthz` 200, a proxied request 200, its own
|
`Now listening on:`, `/healthz` 200, a proxied request 200, its own
|
||||||
`--healthcheck` mode exit 0. What it still cannot do is run a query. EF refuses
|
`--healthcheck` mode exit 0. What it still cannot do is run a query. EF refuses
|
||||||
to compile a LINQ query at run time in a NativeAOT binary — **32 refusals in
|
to compile a LINQ query at run time in a NativeAOT binary — **18 refusals in
|
||||||
the 2026-10-07 probe window**, 30 in the run before it: a window count, not a
|
the 2026-10-07 probe window, 32 before the first query moved off EF** (a window
|
||||||
total, because the background refresh loop retries on its own clock — and the
|
count, not a total: the background refresh loop retries on its own clock) — and
|
||||||
only alternative, `dotnet ef dbcontext optimize
|
the only alternative, `dotnet ef dbcontext optimize
|
||||||
--precompile-queries`, first refused 40 of this tree's queries (parameter-symbol
|
--precompile-queries`, first refused 40 of this tree's queries (parameter-symbol
|
||||||
roots and captures, dotnet/efcore#35887 / #38030 / #35494, fixed only in the
|
roots and captures, dotnet/efcore#35887 / #38030 / #35494, fixed only in the
|
||||||
12.0-preview1 line). Four refusals remain, and they are not a style to rewrite
|
12.0-preview1 line). Four refusals remain, and they are not a style to rewrite
|
||||||
@@ -169,6 +169,42 @@ classifies the status, and is the only thing that can create an engine ban.
|
|||||||
supplied at composition. That is the slice this entry points at (OPEN-79), and
|
supplied at composition. That is the slice this entry points at (OPEN-79), and
|
||||||
the reason it is the *correct* step rather than the cheap one: it removes the
|
the reason it is the *correct* step rather than the cheap one: it removes the
|
||||||
walls instead of routing around them.
|
walls instead of routing around them.
|
||||||
|
|
||||||
|
**The first query moved (2026-10-07).** `dotnet/OpenWaf.Data` (a runtime typed
|
||||||
|
over `System.Data.Common`, no provider package in it) and
|
||||||
|
`dotnet/OpenWaf.Data.Generator` (a Roslyn incremental generator attached to
|
||||||
|
`OpenWaf.Infrastructure` as an analyzer) are that mechanism, first slice. The
|
||||||
|
generator emits, for a `[Table]` class, the column map, the row materializer and
|
||||||
|
an `OrmMeta.Register` call inside a `[ModuleInitializer]` — so the question a
|
||||||
|
NativeAOT binary cannot answer, "what are this type's properties", is never
|
||||||
|
asked. `Query<T>` renders SQL by **walking** the expression tree rather than
|
||||||
|
compiling it, which is the exact difference from EF's pipeline. The supported
|
||||||
|
grammar is a closed set that refuses by name — joins, subqueries, aggregates
|
||||||
|
other than `COUNT`, updates, deletes, JSON columns, method calls — because a
|
||||||
|
renderer that guesses is a renderer that ships wrong SQL.
|
||||||
|
Measured on the AOT binary with the same probe and the same window: query
|
||||||
|
refusals **32 → 18**, `EdgePolicyProvider: reload failed` **1 → 0**, binary
|
||||||
|
**49,609,680 → 49,676,016 bytes**. The 18 are named by their own frames: 14
|
||||||
|
`EdgeStateStore.RefreshAsync`, 2 `BlockStore.WriteBanAsync`, 1
|
||||||
|
`BlockStore.AddOperatorAsync`, 1 admin endpoint. EF still owns every write and
|
||||||
|
every other read; the two layers coexist on one composition root, which is what
|
||||||
|
makes the move incremental rather than a rewrite.
|
||||||
|
|
||||||
|
Two contracts this had to respect, both now asserted rather than assumed. The
|
||||||
|
sqlite timestamp column is EF's `DateTimeOffsetToBinaryConverter` — every row
|
||||||
|
already written says `(localTicks / 1000) * 2048 + (offsetMinutes & 2047)` — and
|
||||||
|
`SqliteTimestampEncodingTests` pins the dialect's read and write to EF's own
|
||||||
|
converter across five instants including a `+05:30` and `DateTimeOffset.MinValue`,
|
||||||
|
including the microsecond truncation that encoding imposes. And the dialect, not
|
||||||
|
the generated code, owns the provider differences: quoting, the paging tail
|
||||||
|
(`LIMIT -1 OFFSET n` on sqlite, `LIMIT 2147483647 OFFSET n` on PostgreSQL), bool
|
||||||
|
as INTEGER versus boolean, timestamp as integer versus `timestamptz`.
|
||||||
|
|
||||||
|
One build trap worth recording: **`-p:PublishAot` on the command line is a
|
||||||
|
global property**, so it reaches every project in the graph — including a
|
||||||
|
`netstandard2.0` analyzer — and the publish fails with `NETSDK1207`. AOT is now
|
||||||
|
switched by `OpenWafAot=true`, which only `OpenWaf.Edge.csproj` turns into
|
||||||
|
`PublishAot`, the same shape as the existing `OpenWafCompiledModel` switch.
|
||||||
* **Keying the ban on ip+UA** (as the analytics `SessionHash` does): a bot that
|
* **Keying the ban on ip+UA** (as the analytics `SessionHash` does): a bot that
|
||||||
varies its UA multiplies into many sources and never reaches the threshold.
|
varies its UA multiplies into many sources and never reaches the threshold.
|
||||||
* **Banning on 5xx because the original wording said `> 400`**: turns an outage
|
* **Banning on 5xx because the original wording said `> 400`**: turns an outage
|
||||||
|
|||||||
@@ -0,0 +1,141 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Collections.Immutable;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using Microsoft.CodeAnalysis;
|
||||||
|
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||||
|
|
||||||
|
namespace OpenWaf.Data.Generator;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Emits the ORM plumbing for a class marked <c>[Table]</c>: the column map, the
|
||||||
|
/// row materializer, and the metadata registration — all as ordinary C#, at
|
||||||
|
/// build time.
|
||||||
|
///
|
||||||
|
/// Why generated rather than reflected: the whole NativeAOT wall on this tree is
|
||||||
|
/// that a compiled binary cannot answer "what are this type's properties" at run
|
||||||
|
/// time. EF's answer to that question is the sentence the probe counts — 32
|
||||||
|
/// refusals in the 2026-10-07 window. Here the answer is a switch the compiler
|
||||||
|
/// wrote, so the question is never asked.
|
||||||
|
///
|
||||||
|
/// The column name is the property name unless a <c>[Column]</c> says otherwise,
|
||||||
|
/// because that is what this schema of record uses: <c>schema.sqlite.sql</c>
|
||||||
|
/// creates <c>"policy_settings"("Key","Value","UpdatedAt")</c>.
|
||||||
|
/// </summary>
|
||||||
|
[Generator]
|
||||||
|
public sealed class EntityOrmGenerator : IIncrementalGenerator
|
||||||
|
{
|
||||||
|
public void Initialize(IncrementalGeneratorInitializationContext context)
|
||||||
|
{
|
||||||
|
var entities = context.SyntaxProvider
|
||||||
|
.ForAttributeWithMetadataName(
|
||||||
|
"OpenWaf.Data.TableAttribute",
|
||||||
|
static (node, _) => node is ClassDeclarationSyntax,
|
||||||
|
static (ctx, _) => Read((INamedTypeSymbol)ctx.TargetSymbol))
|
||||||
|
.Collect();
|
||||||
|
|
||||||
|
context.RegisterSourceOutput(entities, static (spc, entities) =>
|
||||||
|
{
|
||||||
|
foreach (var entity in entities)
|
||||||
|
spc.AddSource("OpenWaf.Data." + entity.ShortName + "Orm.g.cs", Emit(entity));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Entity Read(INamedTypeSymbol type)
|
||||||
|
{
|
||||||
|
var table = AttributeArgument(type, "OpenWaf.Data.TableAttribute") ?? type.Name;
|
||||||
|
var columns = new List<ColumnMapping>();
|
||||||
|
foreach (var member in type.GetMembers().OfType<IPropertySymbol>())
|
||||||
|
{
|
||||||
|
if (member.IsStatic || member.IsIndexer) continue;
|
||||||
|
if (member.GetMethod is null) continue;
|
||||||
|
if (member.DeclaredAccessibility != Accessibility.Public) continue;
|
||||||
|
var name = AttributeArgument(member, "OpenWaf.Data.ColumnAttribute") ?? member.Name;
|
||||||
|
// "global::" is stripped so the switch below can name a type the way a
|
||||||
|
// reader writes it; the generated code uses the same string.
|
||||||
|
columns.Add(new ColumnMapping(
|
||||||
|
member.Name,
|
||||||
|
name,
|
||||||
|
member.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat).Replace("global::", string.Empty)));
|
||||||
|
}
|
||||||
|
return new Entity(
|
||||||
|
type.ContainingNamespace.IsGlobalNamespace ? string.Empty : type.ContainingNamespace.ToDisplayString(),
|
||||||
|
type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat),
|
||||||
|
type.Name,
|
||||||
|
table,
|
||||||
|
columns.ToImmutableArray());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string? AttributeArgument(ISymbol symbol, string attributeName)
|
||||||
|
{
|
||||||
|
var attribute = symbol.GetAttributes()
|
||||||
|
.FirstOrDefault(a => a.AttributeClass?.ToDisplayString() == attributeName);
|
||||||
|
return attribute?.ConstructorArguments.Length > 0 ? attribute.ConstructorArguments[0].Value as string : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Emit(Entity entity)
|
||||||
|
{
|
||||||
|
var sb = new StringBuilder();
|
||||||
|
sb.AppendLine("// <auto-generated/>");
|
||||||
|
sb.AppendLine("// Generated from " + entity.TypeName + " by OpenWaf.Data.Generator. Do not edit.");
|
||||||
|
sb.AppendLine("#nullable enable");
|
||||||
|
sb.AppendLine("using System.Collections.Immutable;");
|
||||||
|
sb.AppendLine("using System.Data.Common;");
|
||||||
|
sb.AppendLine("using System.Runtime.CompilerServices;");
|
||||||
|
sb.AppendLine("using OpenWaf.Data;");
|
||||||
|
sb.AppendLine();
|
||||||
|
if (entity.Namespace.Length > 0) sb.AppendLine("namespace " + entity.Namespace + ";");
|
||||||
|
sb.AppendLine();
|
||||||
|
sb.AppendLine("/// <summary>The generated data access for <c>" + entity.ShortName + "</c>: the table's");
|
||||||
|
sb.AppendLine("/// metadata, its column map and its row materializer. Nothing here is discovered at");
|
||||||
|
sb.AppendLine("/// run time, which is the point.</summary>");
|
||||||
|
sb.AppendLine("public static class " + entity.ShortName + "Orm");
|
||||||
|
sb.AppendLine("{");
|
||||||
|
sb.AppendLine(" [ModuleInitializer]");
|
||||||
|
sb.AppendLine(" internal static void RegisterOpenWafData() =>");
|
||||||
|
sb.AppendLine(" OrmMeta.Register<" + entity.TypeName + ">(");
|
||||||
|
sb.AppendLine(" " + Literal(entity.Table) + ",");
|
||||||
|
sb.AppendLine(" ColumnOf,");
|
||||||
|
sb.AppendLine(" ImmutableArray.Create(" + string.Join(", ", entity.Columns.Select(c => Literal(c.Column))) + "));");
|
||||||
|
sb.AppendLine();
|
||||||
|
sb.AppendLine(" /// <summary>CLR member name to column name. Empty means the member is not a");
|
||||||
|
sb.AppendLine(" /// column of this table, and the query layer says so rather than guessing.</summary>");
|
||||||
|
sb.AppendLine(" public static string ColumnOf(string member) => member switch");
|
||||||
|
sb.AppendLine(" {");
|
||||||
|
foreach (var column in entity.Columns)
|
||||||
|
sb.AppendLine(" " + Literal(column.Member) + " => " + Literal(column.Column) + ",");
|
||||||
|
sb.AppendLine(" _ => string.Empty,");
|
||||||
|
sb.AppendLine(" };");
|
||||||
|
sb.AppendLine();
|
||||||
|
sb.AppendLine(" public static Query<" + entity.TypeName + "> Query(OrmContext db) =>");
|
||||||
|
sb.AppendLine(" new(db, OrmMeta.Get(typeof(" + entity.TypeName + ")), Map);");
|
||||||
|
sb.AppendLine();
|
||||||
|
sb.AppendLine(" /// <summary>Reads one row of " + Literal(entity.Table) + " into a new object. The");
|
||||||
|
sb.AppendLine(" /// ordinals are the order " + "RenderSelect" + " emits, which is the order the");
|
||||||
|
sb.AppendLine(" /// column list was registered in — one list, one order, no name lookups per row.</summary>");
|
||||||
|
sb.AppendLine(" public static " + entity.TypeName + " Map(DbDataReader reader, ISqlDialect dialect) => new " + entity.TypeName);
|
||||||
|
sb.AppendLine(" {");
|
||||||
|
for (var i = 0; i < entity.Columns.Length; i++)
|
||||||
|
sb.AppendLine(" " + entity.Columns[i].Member + " = " + Read(entity.Columns[i], i) + ",");
|
||||||
|
sb.AppendLine(" };");
|
||||||
|
sb.AppendLine("}");
|
||||||
|
return sb.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Read(ColumnMapping column, int ordinal) => column.Type switch
|
||||||
|
{
|
||||||
|
"string" => "RowReader.String(reader, " + ordinal + ")",
|
||||||
|
"bool" => "RowReader.Boolean(reader, " + ordinal + ")",
|
||||||
|
"int" => "RowReader.Int32(reader, " + ordinal + ")",
|
||||||
|
"long" => "RowReader.Int64(reader, " + ordinal + ")",
|
||||||
|
"System.DateTimeOffset" => "RowReader.DateTimeOffset(reader, " + ordinal + ", dialect)",
|
||||||
|
"System.Guid" => "RowReader.Guid(reader, " + ordinal + ")",
|
||||||
|
_ => "RowReader.Required<" + column.Type + ">(reader, " + ordinal + ")",
|
||||||
|
};
|
||||||
|
|
||||||
|
private static string Literal(string value) => "\"" + value.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\"";
|
||||||
|
|
||||||
|
private sealed record Entity(string Namespace, string TypeName, string ShortName, string Table, ImmutableArray<ColumnMapping> Columns);
|
||||||
|
|
||||||
|
private sealed record ColumnMapping(string Member, string Column, string Type);
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
// netstandard2.0 has no IsExternalInit, which the compiler needs for `init`
|
||||||
|
// accessors in records. Roslyn analyzers target netstandard2.0 so they load in
|
||||||
|
// every compiler; this is the standard shim, and the neighbouring project ships
|
||||||
|
// the same one (~/work/tskr/app/lib/IsExternalInit.cs).
|
||||||
|
using System.ComponentModel;
|
||||||
|
|
||||||
|
namespace System.Runtime.CompilerServices;
|
||||||
|
|
||||||
|
[EditorBrowsable(EditorBrowsableState.Never)]
|
||||||
|
internal static class IsExternalInit
|
||||||
|
{
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<!-- The build-time half of the query slice (OPEN-79, wall 3). It emits the row
|
||||||
|
mapping and the table metadata for a [Table] class, so that nothing at run
|
||||||
|
time has to discover what a type is: a NativeAOT binary has no resolver for
|
||||||
|
that question, and asking one is the refusal this slice removes.
|
||||||
|
The shape is the neighbouring deployment's (~/work/tskr/app/lib/MicroOrm/
|
||||||
|
OrmGenerator.cs); the mechanism is Roslyn's incremental generator, and the
|
||||||
|
output is ordinary C# that can be read in obj/ and asserted against. -->
|
||||||
|
<PropertyGroup>
|
||||||
|
<!-- A Roslyn component: the compiler loads it, ILC never sees it. -->
|
||||||
|
<TargetFramework>netstandard2.0</TargetFramework>
|
||||||
|
<LangVersion>latest</LangVersion>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<IsRoslynComponent>true</IsRoslynComponent>
|
||||||
|
<!-- A build-time Roslyn component: ILC never sees it. Without this the AOT
|
||||||
|
publish walks the project graph, reaches a netstandard2.0 project, and
|
||||||
|
answers NETSDK1207 "Ahead-of-time compilation is not supported for the
|
||||||
|
target framework" — measured on 2026-10-07, the first AOT publish after
|
||||||
|
the generator was attached. The neighbouring project guards the same
|
||||||
|
trap with IsAotCompatible=false for its generators (LEAS-728). -->
|
||||||
|
<IsPublishable>false</IsPublishable>
|
||||||
|
<IncludeBuildOutput>false</IncludeBuildOutput>
|
||||||
|
<IsAotCompatible>false</IsAotCompatible>
|
||||||
|
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.14.0" PrivateAssets="all" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<!-- The query half of the NativeAOT slice (OPEN-79, wall 3). No EF, no
|
||||||
|
provider package: everything here is typed over System.Data.Common, and
|
||||||
|
the concrete driver is supplied at composition by the composition root.
|
||||||
|
That is the shape the neighbouring deployment ships (~/work/tskr,
|
||||||
|
app/lib/MicroOrmRuntime), and it is the shape this tree needs because the
|
||||||
|
ADO layer survives a fully static AOT link — measured: Microsoft.Data.Sqlite
|
||||||
|
reads sqlite_version() back from the static binary — while EF's query
|
||||||
|
compilation does not (32 refusals in the 2026-10-07 probe window). -->
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<InternalsVisibleTo Include="OpenWaf.Tests.Unit" />
|
||||||
|
<InternalsVisibleTo Include="OpenWaf.Tests.Integration" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
#nullable enable
|
||||||
|
using System;
|
||||||
|
using System.Data.Common;
|
||||||
|
|
||||||
|
namespace OpenWaf.Data;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// What a generated query needs to run: a driver and a dialect, decided once at
|
||||||
|
/// composition rather than per call.
|
||||||
|
///
|
||||||
|
/// This is the seam that lets the same generated code serve both providers this
|
||||||
|
/// tree ships. It is taken from the neighbouring deployment's
|
||||||
|
/// <c>MicroOrm.OrmContext</c> (<c>~/work/tskr/app/lib/MicroOrmRuntime</c>), which
|
||||||
|
/// keeps the runtime driver-agnostic and supplies Npgsql at composition; here the
|
||||||
|
/// drivers are sqlite and Npgsql, chosen by the same <c>Database:Provider</c>
|
||||||
|
/// switch <c>Program.cs</c> already uses for EF.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class OrmContext
|
||||||
|
{
|
||||||
|
public DbDataSource DataSource { get; }
|
||||||
|
public ISqlDialect Dialect { get; }
|
||||||
|
|
||||||
|
public OrmContext(DbDataSource dataSource, ISqlDialect dialect)
|
||||||
|
{
|
||||||
|
DataSource = dataSource ?? throw new ArgumentNullException(nameof(dataSource));
|
||||||
|
Dialect = dialect ?? throw new ArgumentNullException(nameof(dialect));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The provider-specific half of query rendering and row reading — and only that
|
||||||
|
/// half. The SQL text is built once; what differs is the identifier quoting, the
|
||||||
|
/// paging tail, and how a CLR value crosses to and from the wire.
|
||||||
|
///
|
||||||
|
/// The timestamp members are not decoration. This tree stores a
|
||||||
|
/// <see cref="DateTimeOffset"/> as a binary integer on sqlite and as native
|
||||||
|
/// <c>timestamptz</c> on PostgreSQL — the model does it deliberately, because
|
||||||
|
/// sqlite stores a timestamp as text and then refuses to compare it, which kills
|
||||||
|
/// every "is this ban still live" query at translation time (see
|
||||||
|
/// <c>OpenWafDbContext.StoreTimestampsAsIntegersOnSqlite</c>). A generated
|
||||||
|
/// materializer therefore cannot know how to read the column; the dialect does.
|
||||||
|
/// </summary>
|
||||||
|
public interface ISqlDialect
|
||||||
|
{
|
||||||
|
string Quote(string identifier);
|
||||||
|
|
||||||
|
/// <summary>The placeholder for the parameter at this ordinal, 0-based.</summary>
|
||||||
|
string Param(int index);
|
||||||
|
|
||||||
|
/// <summary>The paging tail, or empty when neither limit nor offset is set.</summary>
|
||||||
|
string Page(int? limit, int? offset);
|
||||||
|
|
||||||
|
string CountAllExpression { get; }
|
||||||
|
|
||||||
|
string PingStatement { get; }
|
||||||
|
|
||||||
|
/// <summary>How this provider stores a <see cref="DateTimeOffset"/> column.</summary>
|
||||||
|
DateTimeOffset ReadDateTimeOffset(DbDataReader reader, int ordinal);
|
||||||
|
|
||||||
|
/// <summary>The value to hand the driver for a DateTimeOffset parameter.</summary>
|
||||||
|
object WriteDateTimeOffset(DateTimeOffset value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>sqlite, the provider the shipped image runs.</summary>
|
||||||
|
public sealed class SqliteDialect : ISqlDialect
|
||||||
|
{
|
||||||
|
public static SqliteDialect Instance { get; } = new();
|
||||||
|
|
||||||
|
public string Quote(string identifier) => "\"" + identifier.Replace("\"", "\"\"", StringComparison.Ordinal) + "\"";
|
||||||
|
|
||||||
|
// Microsoft.Data.Sqlite binds named parameters, so one text works for both
|
||||||
|
// providers and the rendered SQL stays readable in a log.
|
||||||
|
public string Param(int index) => "@p" + index.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||||
|
|
||||||
|
public string Page(int? limit, int? offset)
|
||||||
|
{
|
||||||
|
if (limit is null && offset is null) return string.Empty;
|
||||||
|
// sqlite requires LIMIT before OFFSET, and an OFFSET needs a LIMIT to
|
||||||
|
// anchor it — -1 means "no limit" in sqlite's own grammar.
|
||||||
|
return " LIMIT " + (limit ?? -1).ToString(System.Globalization.CultureInfo.InvariantCulture)
|
||||||
|
+ (offset is null ? string.Empty : " OFFSET " + offset.Value.ToString(System.Globalization.CultureInfo.InvariantCulture));
|
||||||
|
}
|
||||||
|
|
||||||
|
public string CountAllExpression => "COUNT(*)";
|
||||||
|
|
||||||
|
public string PingStatement => "SELECT 1";
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The integer EF writes for this column, read back. The model puts a
|
||||||
|
/// <see cref="DateTimeOffset"/> through EF's <c>DateTimeOffsetToBinaryConverter</c>
|
||||||
|
/// on sqlite, and that encoding is the storage contract of every row the admin
|
||||||
|
/// API has ever written — so this is not a format this project chose. It is
|
||||||
|
/// reproduced here as <c>(localTicks / 1000) * 2048 + (offsetMinutes & 2047)</c>
|
||||||
|
/// and asserted equal to EF's own converter over a spread of instants
|
||||||
|
/// (positive, negative and half-hour offsets, and DateTime.MinValue) in
|
||||||
|
/// <c>SqliteTimestampEncodingTests</c>, so a provider upgrade that changes it
|
||||||
|
/// is red in a test rather than wrong in production. Note the /1000: this
|
||||||
|
/// column has microsecond resolution, and a round trip through it drops the
|
||||||
|
/// sub-microsecond digits. That is EF's behaviour, not a bug added here.
|
||||||
|
/// </summary>
|
||||||
|
public DateTimeOffset ReadDateTimeOffset(DbDataReader reader, int ordinal)
|
||||||
|
{
|
||||||
|
var stored = reader.GetInt64(ordinal);
|
||||||
|
var offsetMinutes = (int)(stored & 2047);
|
||||||
|
if (offsetMinutes >= 1024) offsetMinutes -= 2048;
|
||||||
|
return new DateTimeOffset((stored >> 11) * 1000, TimeSpan.FromMinutes(offsetMinutes));
|
||||||
|
}
|
||||||
|
|
||||||
|
public object WriteDateTimeOffset(DateTimeOffset value) =>
|
||||||
|
(value.Ticks / 1000) * 2048 + ((int)value.Offset.TotalMinutes & 2047);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>PostgreSQL, the provider a real deployment runs (migrations are its schema of record).</summary>
|
||||||
|
public sealed class PostgresDialect : ISqlDialect
|
||||||
|
{
|
||||||
|
public static PostgresDialect Instance { get; } = new();
|
||||||
|
|
||||||
|
public string Quote(string identifier) => "\"" + identifier.Replace("\"", "\"\"", StringComparison.Ordinal) + "\"";
|
||||||
|
|
||||||
|
public string Param(int index) => "@p" + index.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||||
|
|
||||||
|
public string Page(int? limit, int? offset)
|
||||||
|
{
|
||||||
|
if (limit is null && offset is null) return string.Empty;
|
||||||
|
return " LIMIT " + (limit ?? int.MaxValue).ToString(System.Globalization.CultureInfo.InvariantCulture)
|
||||||
|
+ (offset is null ? string.Empty : " OFFSET " + offset.Value.ToString(System.Globalization.CultureInfo.InvariantCulture));
|
||||||
|
}
|
||||||
|
|
||||||
|
public string CountAllExpression => "COUNT(*)";
|
||||||
|
|
||||||
|
public string PingStatement => "SELECT 1";
|
||||||
|
|
||||||
|
public DateTimeOffset ReadDateTimeOffset(DbDataReader reader, int ordinal) => reader.GetFieldValueAsync<DateTimeOffset>(ordinal).GetAwaiter().GetResult();
|
||||||
|
|
||||||
|
public object WriteDateTimeOffset(DateTimeOffset value) => value;
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
#nullable enable
|
||||||
|
using System;
|
||||||
|
using System.Collections.Concurrent;
|
||||||
|
using System.Collections.Immutable;
|
||||||
|
using System.Diagnostics.CodeAnalysis;
|
||||||
|
|
||||||
|
namespace OpenWaf.Data;
|
||||||
|
|
||||||
|
/// <summary>Marks a class as a row of a table. The name is the table; the
|
||||||
|
/// generator reads it and emits the mapping, so nothing at run time has to ask a
|
||||||
|
/// type what it is.</summary>
|
||||||
|
[AttributeUsage(AttributeTargets.Class)]
|
||||||
|
public sealed class TableAttribute(string name) : Attribute
|
||||||
|
{
|
||||||
|
public string Name { get; } = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Names the column a property maps to when it is not the snake_case of
|
||||||
|
/// the property name.</summary>
|
||||||
|
[AttributeUsage(AttributeTargets.Property)]
|
||||||
|
public sealed class ColumnAttribute(string name) : Attribute
|
||||||
|
{
|
||||||
|
public string Name { get; } = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The table's metadata, registered by generated code at module start-up.
|
||||||
|
///
|
||||||
|
/// This is the piece that makes the whole thing AOT-safe: the mapping from a CLR
|
||||||
|
/// member name to a column name is a function the compiler emitted, not something
|
||||||
|
/// a run-time resolver discovers. A NativeAOT binary has no resolver to fall back
|
||||||
|
/// on, and asking for one is exactly the refusal this slice exists to remove.
|
||||||
|
/// Taken from <c>MicroOrm.OrmMeta</c> in the neighbouring deployment.
|
||||||
|
/// </summary>
|
||||||
|
public static class OrmMeta
|
||||||
|
{
|
||||||
|
private static readonly ConcurrentDictionary<Type, TableMeta> Map = new();
|
||||||
|
|
||||||
|
public static void Register<T>(string table, Func<string, string> columnOf, ImmutableArray<string> columns) =>
|
||||||
|
Map[typeof(T)] = new TableMeta(table, columnOf, columns);
|
||||||
|
|
||||||
|
public static bool TryGet(Type type, [MaybeNullWhen(false)] out TableMeta meta) => Map.TryGetValue(type, out meta);
|
||||||
|
|
||||||
|
public static TableMeta Get(Type type) =>
|
||||||
|
Map.TryGetValue(type, out var meta)
|
||||||
|
? meta
|
||||||
|
: throw new InvalidOperationException(
|
||||||
|
$"No generated ORM metadata is registered for {type.FullName}. The type needs [Table] and the "
|
||||||
|
+ "OpenWaf.Data.Generator analyzer attached to the project that declares it.");
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed record TableMeta(string Table, Func<string, string> ColumnOf, ImmutableArray<string> Columns);
|
||||||
@@ -0,0 +1,339 @@
|
|||||||
|
#nullable enable
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Data;
|
||||||
|
using System.Data.Common;
|
||||||
|
using System.Globalization;
|
||||||
|
using System.Linq.Expressions;
|
||||||
|
using System.Reflection;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace OpenWaf.Data;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A typed query whose SQL is rendered from an expression tree that is walked,
|
||||||
|
/// never compiled.
|
||||||
|
///
|
||||||
|
/// That last clause is the whole reason this type exists. EF answers the same
|
||||||
|
/// shape under NativeAOT with <c>Query wasn't precompiled and dynamic code isn't
|
||||||
|
/// supported with NativeAOT</c> — 32 of them in the 2026-10-07 probe window
|
||||||
|
/// before the first query moved off EF, 18 after —
|
||||||
|
/// because its query pipeline compiles expression trees into IL at run time.
|
||||||
|
/// Walking the tree with a switch over <see cref="ExpressionType"/> needs no
|
||||||
|
/// dynamic code, and the row materializer is a <c>Func<DbDataReader,T></c>
|
||||||
|
/// the compiler emitted, so there is nothing left for the runtime to generate.
|
||||||
|
/// The mechanism is the neighbouring deployment's
|
||||||
|
/// (<c>~/work/tskr/app/lib/MicroOrmRuntime/Query.cs</c>, 1,219 lines); this is the
|
||||||
|
/// first slice of it, sized to the one query this tree has moved so far.
|
||||||
|
///
|
||||||
|
/// <b>The supported grammar is a closed set, and it says so.</b> Anything outside
|
||||||
|
/// it throws <see cref="UnsupportedQueryNodeException"/> naming the node, rather
|
||||||
|
/// than rendering SQL that is quietly wrong. What is supported today: comparisons
|
||||||
|
/// (<c>== != < <= > >=</c>) between a column and a value, null tests,
|
||||||
|
/// <c>&&</c>, <c>||</c>, <c>!</c>, captured locals and closure fields on the
|
||||||
|
/// value side, ordering, <c>Take</c>/<c>Skip</c>. What is not: joins, subqueries,
|
||||||
|
/// aggregates other than <c>Count</c>, updates and deletes, JSON columns, enum
|
||||||
|
/// comparisons. Each of those is a decision with a cost, not an oversight — and
|
||||||
|
/// <c>RenderSelect</c> is public so the rendered text can be asserted without a
|
||||||
|
/// database, which is how the neighbouring project tests its own renderers.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class Query<T>
|
||||||
|
{
|
||||||
|
private readonly OrmContext _db;
|
||||||
|
private readonly Func<DbDataReader, ISqlDialect, T> _map;
|
||||||
|
private readonly TableMeta _meta;
|
||||||
|
private readonly List<string> _where = [];
|
||||||
|
private readonly List<(string Column, bool Descending)> _order = [];
|
||||||
|
private readonly List<object?> _args = [];
|
||||||
|
private int? _limit;
|
||||||
|
private int? _offset;
|
||||||
|
|
||||||
|
public Query(OrmContext db, TableMeta meta, Func<DbDataReader, ISqlDialect, T> map)
|
||||||
|
{
|
||||||
|
_db = db;
|
||||||
|
_meta = meta;
|
||||||
|
_map = map;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Query<T> Where(Expression<Func<T, bool>> predicate)
|
||||||
|
{
|
||||||
|
// No extra parentheses here: Translate parenthesizes every binary term it
|
||||||
|
// emits, so a WHERE over one term reads as WHERE (x = @p0) and a WHERE over
|
||||||
|
// several reads as WHERE ((…) AND (…)) rather than a stack of brackets.
|
||||||
|
_where.Add(Translate(predicate.Body, predicate.Parameters[0]));
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Query<T> OrderBy(Expression<Func<T, object?>> selector) => Order(selector, false);
|
||||||
|
public Query<T> OrderByDescending(Expression<Func<T, object?>> selector) => Order(selector, true);
|
||||||
|
|
||||||
|
private Query<T> Order(Expression<Func<T, object?>> selector, bool descending)
|
||||||
|
{
|
||||||
|
_order.Add((ColumnOf(selector.Body, selector.Parameters[0]), descending));
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Query<T> Take(int n) { _limit = n; return this; }
|
||||||
|
public Query<T> Skip(int n) { _offset = n; return this; }
|
||||||
|
|
||||||
|
/// <summary>The SELECT this query would run, with the parameters it binds in
|
||||||
|
/// the same order. Public on purpose: the renderer is the test seam, and a
|
||||||
|
/// wrong query should be red against a string, not only against a database.</summary>
|
||||||
|
public string RenderSelect()
|
||||||
|
{
|
||||||
|
var sb = new StringBuilder("SELECT ");
|
||||||
|
var quoted = new List<string>(_meta.Columns.Length);
|
||||||
|
foreach (var column in _meta.Columns) quoted.Add(_db.Dialect.Quote(column));
|
||||||
|
sb.Append(string.Join(", ", quoted));
|
||||||
|
return AppendFrom(sb);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The COUNT this query would run for <see cref="CountAsync"/>.</summary>
|
||||||
|
public string RenderCount() => AppendFrom(new StringBuilder("SELECT " + _db.Dialect.CountAllExpression));
|
||||||
|
|
||||||
|
private string AppendFrom(StringBuilder sb)
|
||||||
|
{
|
||||||
|
sb.Append(" FROM ").Append(_db.Dialect.Quote(_meta.Table));
|
||||||
|
if (_where.Count > 0) sb.Append(" WHERE ").Append(string.Join(" AND ", _where));
|
||||||
|
if (_order.Count > 0)
|
||||||
|
{
|
||||||
|
sb.Append(" ORDER BY ");
|
||||||
|
var terms = new List<string>(_order.Count);
|
||||||
|
foreach (var o in _order)
|
||||||
|
terms.Add(_db.Dialect.Quote(o.Column) + (o.Descending ? " DESC" : " ASC"));
|
||||||
|
sb.Append(string.Join(", ", terms));
|
||||||
|
}
|
||||||
|
sb.Append(_db.Dialect.Page(_limit, _offset));
|
||||||
|
return sb.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public IReadOnlyList<object?> Arguments => _args;
|
||||||
|
|
||||||
|
public async Task<List<T>> ToListAsync(CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
var sql = RenderSelect();
|
||||||
|
await using var connection = await _db.DataSource.OpenConnectionAsync(ct);
|
||||||
|
await using var command = connection.CreateCommand();
|
||||||
|
command.CommandText = sql;
|
||||||
|
Bind(command);
|
||||||
|
await using var reader = await command.ExecuteReaderAsync(ct);
|
||||||
|
var rows = new List<T>();
|
||||||
|
while (await reader.ReadAsync(ct)) rows.Add(_map(reader, _db.Dialect));
|
||||||
|
return rows;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<long> CountAsync(CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
var sql = RenderCount();
|
||||||
|
await using var connection = await _db.DataSource.OpenConnectionAsync(ct);
|
||||||
|
await using var command = connection.CreateCommand();
|
||||||
|
command.CommandText = sql;
|
||||||
|
Bind(command);
|
||||||
|
var value = await command.ExecuteScalarAsync(ct);
|
||||||
|
return Convert.ToInt64(value, CultureInfo.InvariantCulture);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<T?> FirstOrDefaultAsync(CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
_limit = 1;
|
||||||
|
var rows = await ToListAsync(ct);
|
||||||
|
return rows.Count > 0 ? rows[0] : default;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Bind(DbCommand command)
|
||||||
|
{
|
||||||
|
for (var i = 0; i < _args.Count; i++)
|
||||||
|
{
|
||||||
|
var parameter = command.CreateParameter();
|
||||||
|
parameter.ParameterName = "@p" + i.ToString(CultureInfo.InvariantCulture);
|
||||||
|
parameter.Value = _args[i] ?? DBNull.Value;
|
||||||
|
command.Parameters.Add(parameter);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- the translator ----------------------------------------------------
|
||||||
|
|
||||||
|
private string Translate(Expression expression, ParameterExpression entity)
|
||||||
|
{
|
||||||
|
switch (expression)
|
||||||
|
{
|
||||||
|
case UnaryExpression { NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked } convert:
|
||||||
|
return Translate(convert.Operand, entity);
|
||||||
|
|
||||||
|
case UnaryExpression { NodeType: ExpressionType.Not } not:
|
||||||
|
return "NOT (" + Translate(not.Operand, entity) + ")";
|
||||||
|
|
||||||
|
case BinaryExpression binary:
|
||||||
|
return TranslateBinary(binary, entity);
|
||||||
|
|
||||||
|
case MemberExpression flag when IsColumn(flag, entity):
|
||||||
|
// A bare boolean column, rendered as a truth test: both providers
|
||||||
|
// this tree runs store a bool as 1/0.
|
||||||
|
return _db.Dialect.Quote(ColumnOf(flag, entity)) + " = 1";
|
||||||
|
|
||||||
|
case MethodCallExpression call:
|
||||||
|
throw new UnsupportedQueryNodeException(
|
||||||
|
$"method call '{call.Method.DeclaringType?.Name}.{call.Method.Name}'");
|
||||||
|
|
||||||
|
default:
|
||||||
|
throw new UnsupportedQueryNodeException(expression.NodeType.ToString());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private string TranslateBinary(BinaryExpression binary, ParameterExpression entity)
|
||||||
|
{
|
||||||
|
switch (binary.NodeType)
|
||||||
|
{
|
||||||
|
case ExpressionType.AndAlso:
|
||||||
|
return "(" + Translate(binary.Left, entity) + " AND " + Translate(binary.Right, entity) + ")";
|
||||||
|
case ExpressionType.OrElse:
|
||||||
|
return "(" + Translate(binary.Left, entity) + " OR " + Translate(binary.Right, entity) + ")";
|
||||||
|
}
|
||||||
|
|
||||||
|
var left = Operand(binary.Left, entity);
|
||||||
|
var right = Operand(binary.Right, entity);
|
||||||
|
|
||||||
|
// A null on either side is an IS [NOT] NULL test, never an equality with a
|
||||||
|
// parameter: "col = NULL" is unknown, not false, and a ban filter built that
|
||||||
|
// way silently stops matching the rows it was written for.
|
||||||
|
if (left.IsNull && right.IsNull)
|
||||||
|
throw new UnsupportedQueryNodeException("null compared with null");
|
||||||
|
if (left.IsNull) return NullTest(right.Column, binary.NodeType);
|
||||||
|
if (right.IsNull) return NullTest(left.Column, binary.NodeType);
|
||||||
|
|
||||||
|
var op = binary.NodeType switch
|
||||||
|
{
|
||||||
|
ExpressionType.Equal => "=",
|
||||||
|
ExpressionType.NotEqual => "<>",
|
||||||
|
ExpressionType.GreaterThan => ">",
|
||||||
|
ExpressionType.GreaterThanOrEqual => ">=",
|
||||||
|
ExpressionType.LessThan => "<",
|
||||||
|
ExpressionType.LessThanOrEqual => "<=",
|
||||||
|
_ => throw new UnsupportedQueryNodeException(binary.NodeType.ToString()),
|
||||||
|
};
|
||||||
|
|
||||||
|
// One side is the column, the other is a value already mapped for this
|
||||||
|
// provider. The parameter is appended before the placeholder is written, so
|
||||||
|
// the numbering and the bind order cannot disagree.
|
||||||
|
var column = left.Column ?? right.Column
|
||||||
|
?? throw new UnsupportedQueryNodeException("a comparison with no column on either side");
|
||||||
|
_args.Add(left.Column is null ? left.Value : right.Value);
|
||||||
|
// Parenthesized even though SQL's own precedence would usually allow it
|
||||||
|
// without: a rendered predicate is read by a human in a log, and a test
|
||||||
|
// that mixes AND and OR should not depend on who remembers the table.
|
||||||
|
return "(" + _db.Dialect.Quote(column) + " " + op + " " + _db.Dialect.Param(_args.Count - 1) + ")";
|
||||||
|
}
|
||||||
|
|
||||||
|
private string NullTest(string? column, ExpressionType nodeType)
|
||||||
|
{
|
||||||
|
if (column is null)
|
||||||
|
throw new UnsupportedQueryNodeException("a null test with no column to test");
|
||||||
|
return nodeType switch
|
||||||
|
{
|
||||||
|
ExpressionType.Equal => "(" + _db.Dialect.Quote(column) + " IS NULL)",
|
||||||
|
ExpressionType.NotEqual => "(" + _db.Dialect.Quote(column) + " IS NOT NULL)",
|
||||||
|
_ => throw new UnsupportedQueryNodeException(nodeType.ToString() + " against null"),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private readonly record struct OperandResult(string? Column, object? Value, bool IsNull);
|
||||||
|
|
||||||
|
private OperandResult Operand(Expression expression, ParameterExpression entity)
|
||||||
|
{
|
||||||
|
var unwrapped = Unwrap(expression);
|
||||||
|
if (unwrapped is ConstantExpression { Value: null }) return new OperandResult(null, null, true);
|
||||||
|
if (IsColumn(unwrapped, entity)) return new OperandResult(ColumnOf(unwrapped, entity), null, false);
|
||||||
|
var mapped = Value(unwrapped, entity);
|
||||||
|
// A captured null is a null test too. Rendering it as "col = @p0" bound to
|
||||||
|
// DBNull parses, runs, and matches nothing — the quietest wrong answer
|
||||||
|
// there is, and the one a nullable ban expiry produces.
|
||||||
|
return new OperandResult(null, mapped, mapped is null);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Expression Unwrap(Expression expression) =>
|
||||||
|
expression is UnaryExpression { NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked } convert
|
||||||
|
? Unwrap(convert.Operand)
|
||||||
|
: expression;
|
||||||
|
|
||||||
|
private static bool IsColumn(Expression expression, ParameterExpression entity) =>
|
||||||
|
Unwrap(expression) is MemberExpression member && RootOf(member) == entity;
|
||||||
|
|
||||||
|
private static Expression? RootOf(Expression expression) =>
|
||||||
|
expression switch
|
||||||
|
{
|
||||||
|
MemberExpression member => RootOf(member.Expression!),
|
||||||
|
UnaryExpression unary => RootOf(unary.Operand),
|
||||||
|
ParameterExpression parameter => parameter,
|
||||||
|
_ => null,
|
||||||
|
};
|
||||||
|
|
||||||
|
private string ColumnOf(Expression expression, ParameterExpression entity)
|
||||||
|
{
|
||||||
|
if (Unwrap(expression) is not MemberExpression member)
|
||||||
|
throw new UnsupportedQueryNodeException("an ordering or test that is not a column");
|
||||||
|
var name = member.Member.Name;
|
||||||
|
var column = _meta.ColumnOf(name);
|
||||||
|
if (column.Length == 0)
|
||||||
|
throw new UnsupportedQueryNodeException($"member '{name}' is not a column of {_meta.Table}");
|
||||||
|
return column;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The value side of a comparison: a literal, a captured local, or a
|
||||||
|
/// closure field. Reading a closure field is reflection over a field the
|
||||||
|
/// compiler generated for a lambda — the same move the neighbouring
|
||||||
|
/// deployment's renderer makes, and the one its AOT deployment proves works.</summary>
|
||||||
|
private object? Value(Expression expression, ParameterExpression entity)
|
||||||
|
{
|
||||||
|
expression = Unwrap(expression);
|
||||||
|
switch (expression)
|
||||||
|
{
|
||||||
|
case ConstantExpression constant:
|
||||||
|
return MapValue(constant.Value);
|
||||||
|
|
||||||
|
case MemberExpression member:
|
||||||
|
{
|
||||||
|
// The root of a captured variable is a ConstantExpression holding
|
||||||
|
// the closure object itself. It is the OWNER of the field read, not
|
||||||
|
// a value to bind — mapping it as a parameter is how a captured
|
||||||
|
// local turns into "a parameter of type <>c__DisplayClass10_0".
|
||||||
|
object? owner = null;
|
||||||
|
if (member.Expression is not null)
|
||||||
|
{
|
||||||
|
var ownerExpression = Unwrap(member.Expression);
|
||||||
|
owner = ownerExpression is ConstantExpression root ? root.Value : Value(ownerExpression, entity);
|
||||||
|
}
|
||||||
|
|
||||||
|
var raw = member.Member switch
|
||||||
|
{
|
||||||
|
FieldInfo field => field.GetValue(owner),
|
||||||
|
PropertyInfo property => property.GetValue(owner),
|
||||||
|
_ => throw new UnsupportedQueryNodeException($"member '{member.Member.Name}' on the value side"),
|
||||||
|
};
|
||||||
|
return MapValue(raw);
|
||||||
|
}
|
||||||
|
|
||||||
|
default:
|
||||||
|
throw new UnsupportedQueryNodeException(expression.NodeType.ToString() + " on the value side");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private object? MapValue(object? value) => value switch
|
||||||
|
{
|
||||||
|
null => null,
|
||||||
|
DateTimeOffset instant => _db.Dialect.WriteDateTimeOffset(instant),
|
||||||
|
bool flag => flag ? 1 : 0,
|
||||||
|
string or byte or sbyte or short or ushort or int or uint or long or ulong or float or double or decimal or Guid => value,
|
||||||
|
_ => throw new UnsupportedQueryNodeException(
|
||||||
|
$"a parameter of type {value.GetType().Name}; the generated query layer names the CLR types it binds"),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A query shape this layer refuses, said by name at the call site
|
||||||
|
/// rather than answered with SQL that looks right.</summary>
|
||||||
|
public sealed class UnsupportedQueryNodeException(string what)
|
||||||
|
: NotSupportedException($"OpenWaf.Data cannot render {what}. Either extend the renderer or leave the query to EF.")
|
||||||
|
{
|
||||||
|
public string What { get; } = what;
|
||||||
|
}
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
#nullable enable
|
||||||
|
using System;
|
||||||
|
using System.Data.Common;
|
||||||
|
|
||||||
|
namespace OpenWaf.Data;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The one place a column crosses into a CLR value.
|
||||||
|
///
|
||||||
|
/// Generated code calls these instead of inlining <c>reader.GetString(i)</c> for
|
||||||
|
/// two reasons. A wrong read is then wrong in one place, and the provider
|
||||||
|
/// differences have somewhere to live: sqlite stores a bool as an INTEGER and
|
||||||
|
/// PostgreSQL as a boolean, and a timestamp as an integer and as timestamptz. The
|
||||||
|
/// generated materializer cannot know which provider it is running against; this
|
||||||
|
/// can ask.
|
||||||
|
/// </summary>
|
||||||
|
public static class RowReader
|
||||||
|
{
|
||||||
|
public static string String(DbDataReader reader, int ordinal) =>
|
||||||
|
reader.IsDBNull(ordinal) ? throw Null(ordinal, "string") : reader.GetString(ordinal);
|
||||||
|
|
||||||
|
public static bool Boolean(DbDataReader reader, int ordinal)
|
||||||
|
{
|
||||||
|
if (reader.IsDBNull(ordinal)) throw Null(ordinal, "bool");
|
||||||
|
// sqlite answers an INTEGER column, Npgsql a boolean one.
|
||||||
|
return reader.GetValue(ordinal) switch
|
||||||
|
{
|
||||||
|
bool flag => flag,
|
||||||
|
long number => number != 0,
|
||||||
|
int number => number != 0,
|
||||||
|
var other => throw Mismatch(ordinal, "bool", other),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int Int32(DbDataReader reader, int ordinal)
|
||||||
|
{
|
||||||
|
if (reader.IsDBNull(ordinal)) throw Null(ordinal, "int");
|
||||||
|
return reader.GetValue(ordinal) switch
|
||||||
|
{
|
||||||
|
int number => number,
|
||||||
|
long number => checked((int)number),
|
||||||
|
var other => throw Mismatch(ordinal, "int", other),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public static long Int64(DbDataReader reader, int ordinal)
|
||||||
|
{
|
||||||
|
if (reader.IsDBNull(ordinal)) throw Null(ordinal, "long");
|
||||||
|
return reader.GetValue(ordinal) switch
|
||||||
|
{
|
||||||
|
long number => number,
|
||||||
|
int number => number,
|
||||||
|
var other => throw Mismatch(ordinal, "long", other),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public static DateTimeOffset DateTimeOffset(DbDataReader reader, int ordinal, ISqlDialect dialect)
|
||||||
|
{
|
||||||
|
if (reader.IsDBNull(ordinal)) throw Null(ordinal, "DateTimeOffset");
|
||||||
|
return dialect.ReadDateTimeOffset(reader, ordinal);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Guid Guid(DbDataReader reader, int ordinal)
|
||||||
|
{
|
||||||
|
if (reader.IsDBNull(ordinal)) throw Null(ordinal, "Guid");
|
||||||
|
return reader.GetFieldValue<Guid>(ordinal);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A CLR type this layer has no named read for. It still reads — the
|
||||||
|
/// driver's own conversion is used — so an entity gains a plain column without
|
||||||
|
/// the generator having to know about it, and a column the driver cannot
|
||||||
|
/// convert fails with the ordinal and the type in the message.</summary>
|
||||||
|
public static T Required<T>(DbDataReader reader, int ordinal)
|
||||||
|
{
|
||||||
|
if (reader.IsDBNull(ordinal)) throw Null(ordinal, typeof(T).Name);
|
||||||
|
return reader.GetFieldValue<T>(ordinal);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static InvalidOperationException Null(int ordinal, string type) =>
|
||||||
|
new($"Column {ordinal} is NULL but the generated mapping for {type} does not allow it.");
|
||||||
|
|
||||||
|
private static InvalidCastException Mismatch(int ordinal, string expected, object actual) =>
|
||||||
|
new($"Column {ordinal} came back as {actual.GetType().Name} and the generated mapping expects {expected}.");
|
||||||
|
}
|
||||||
@@ -1,5 +1,19 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||||
|
|
||||||
|
<PropertyGroup Condition="'$(OpenWafAot)' == 'true'">
|
||||||
|
<!-- AOT is a property of this application, not of every project in its graph.
|
||||||
|
Passing -p:PublishAot on the command line makes it a global property, which
|
||||||
|
then reaches the referenced Roslyn analyzer — a netstandard2.0 project — and
|
||||||
|
the publish dies with NETSDK1207 "Ahead-of-time compilation is not supported
|
||||||
|
for the target framework" (measured 2026-10-07, the first publish after the
|
||||||
|
generator was attached). The switch this tree already uses for the same
|
||||||
|
reason is OpenWafCompiledModel: a custom global property that only this
|
||||||
|
project acts on. -->
|
||||||
|
<PublishAot>true</PublishAot>
|
||||||
|
<InvariantGlobalization>true</InvariantGlobalization>
|
||||||
|
<DebugType>none</DebugType>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<TargetFramework>net10.0</TargetFramework>
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
|
|||||||
@@ -66,6 +66,9 @@ builder.Services.AddSingleton(sp => sp.GetRequiredService<IOptions<EdgePolicyOpt
|
|||||||
var provider = builder.Configuration["Database:Provider"] ?? "sqlite";
|
var provider = builder.Configuration["Database:Provider"] ?? "sqlite";
|
||||||
var connectionString = builder.Configuration.GetConnectionString("OpenWaf")
|
var connectionString = builder.Configuration.GetConnectionString("OpenWaf")
|
||||||
?? "Data Source=openwaf.db";
|
?? "Data Source=openwaf.db";
|
||||||
|
// The generated query layer, on the same provider switch as EF: one composition
|
||||||
|
// root decides the driver and the dialect for both halves (OPEN-79, wall 3).
|
||||||
|
builder.Services.AddOpenWafData(provider, connectionString);
|
||||||
builder.Services.AddDbContext<OpenWafDbContext>(options =>
|
builder.Services.AddDbContext<OpenWafDbContext>(options =>
|
||||||
{
|
{
|
||||||
if (provider.Equals("postgres", StringComparison.OrdinalIgnoreCase)) options.UseNpgsql(connectionString);
|
if (provider.Equals("postgres", StringComparison.OrdinalIgnoreCase)) options.UseNpgsql(connectionString);
|
||||||
|
|||||||
@@ -2,6 +2,13 @@
|
|||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\OpenWaf.Domain\OpenWaf.Domain.csproj" />
|
<ProjectReference Include="..\OpenWaf.Domain\OpenWaf.Domain.csproj" />
|
||||||
|
<!-- The generated query layer (OPEN-79, wall 3). The runtime is an ordinary
|
||||||
|
reference; the generator is attached as an analyzer so it runs inside this
|
||||||
|
compilation and emits the mapping for the [Table] classes declared here. -->
|
||||||
|
<ProjectReference Include="..\OpenWaf.Data\OpenWaf.Data.csproj" />
|
||||||
|
<ProjectReference Include="..\OpenWaf.Data.Generator\OpenWaf.Data.Generator.csproj"
|
||||||
|
OutputItemType="Analyzer" ReferenceOutputAssembly="false" PrivateAssets="all"
|
||||||
|
UndefineProperties="PublishAot;SelfContained;RuntimeIdentifier" />
|
||||||
<!-- BackgroundService, DI and options come from the shared framework;
|
<!-- BackgroundService, DI and options come from the shared framework;
|
||||||
an explicit PackageReference for them would be pruned by NuGet. -->
|
an explicit PackageReference for them would be pruned by NuGet. -->
|
||||||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||||
|
|||||||
@@ -61,9 +61,18 @@ public sealed class EdgePolicyProvider
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
using var scope = _scopeFactory.CreateScope();
|
using var scope = _scopeFactory.CreateScope();
|
||||||
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
|
|
||||||
var token = ct;
|
var token = ct;
|
||||||
var rows = await db.PolicySettings.AsNoTracking().ToListAsync(token);
|
// The read moved to the generated query layer (OPEN-79, wall 3). EF
|
||||||
|
// answers this exact query — a whole-table read with no predicate — with
|
||||||
|
// "Query wasn't precompiled and dynamic code isn't supported with
|
||||||
|
// NativeAOT" in an AOT binary, and it was the first refusal in the probe
|
||||||
|
// log. The SQL is rendered from the expression tree by walking it, and the
|
||||||
|
// row materializer is a function the compiler emitted, so there is nothing
|
||||||
|
// left for the run time to generate. The writes below still go through EF;
|
||||||
|
// they are the next ones standing.
|
||||||
|
var rows = await PolicySettingOrm
|
||||||
|
.Query(scope.ServiceProvider.GetRequiredService<OpenWaf.Data.OrmContext>())
|
||||||
|
.ToListAsync(token);
|
||||||
_current = ApplyOverrides(_current, rows);
|
_current = ApplyOverrides(_current, rows);
|
||||||
Interlocked.Exchange(ref _reloadFailures, 0);
|
Interlocked.Exchange(ref _reloadFailures, 0);
|
||||||
Volatile.Write(ref _lastReloadError, null);
|
Volatile.Write(ref _lastReloadError, null);
|
||||||
|
|||||||
@@ -0,0 +1,41 @@
|
|||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using OpenWaf.Data;
|
||||||
|
|
||||||
|
namespace OpenWaf.Infrastructure.Persistence;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Composition of the generated query layer: the driver and the dialect, chosen by
|
||||||
|
/// the same <c>Database:Provider</c> switch that chooses EF's provider.
|
||||||
|
///
|
||||||
|
/// This is the seam the neighbouring deployment uses the same way — its runtime is
|
||||||
|
/// driver-agnostic over <c>System.Data.Common</c> and Npgsql is supplied at
|
||||||
|
/// composition. Keeping the choice in one place is what lets the same generated
|
||||||
|
/// code serve sqlite (the shipped image) and PostgreSQL (the migrations' provider)
|
||||||
|
/// without either one knowing about the other.
|
||||||
|
/// </summary>
|
||||||
|
public static class OpenWafDataComposition
|
||||||
|
{
|
||||||
|
public static IServiceCollection AddOpenWafData(this IServiceCollection services, string provider, string connectionString)
|
||||||
|
{
|
||||||
|
var useSqlite = !provider.Equals("postgres", StringComparison.OrdinalIgnoreCase);
|
||||||
|
|
||||||
|
services.AddSingleton(_ => useSqlite
|
||||||
|
? new OrmContext(SqliteDataSource(connectionString), SqliteDialect.Instance)
|
||||||
|
: new OrmContext(PostgresDataSource(connectionString), PostgresDialect.Instance));
|
||||||
|
|
||||||
|
return services;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static System.Data.Common.DbDataSource SqliteDataSource(string connectionString)
|
||||||
|
{
|
||||||
|
// Microsoft.Data.Sqlite needs the native bundle registered before the
|
||||||
|
// first connection opens. EF does this when its sqlite provider is
|
||||||
|
// constructed; a raw data source does not get to assume that happened
|
||||||
|
// first, and the order here is not guaranteed. The call is idempotent.
|
||||||
|
SQLitePCL.Batteries.Init();
|
||||||
|
return Microsoft.Data.Sqlite.SqliteFactory.Instance.CreateDataSource(connectionString);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static System.Data.Common.DbDataSource PostgresDataSource(string connectionString) =>
|
||||||
|
Npgsql.NpgsqlDataSource.Create(connectionString);
|
||||||
|
}
|
||||||
@@ -236,6 +236,7 @@ public sealed class OpenWafDbContext(DbContextOptions<OpenWafDbContext> options)
|
|||||||
/// from configuration. Stored as text on purpose: the set of knobs is small and
|
/// from configuration. Stored as text on purpose: the set of knobs is small and
|
||||||
/// a column per knob would need a migration every time one is added.
|
/// a column per knob would need a migration every time one is added.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
[OpenWaf.Data.Table("policy_settings")]
|
||||||
public sealed class PolicySetting
|
public sealed class PolicySetting
|
||||||
{
|
{
|
||||||
public string Key { get; init; } = string.Empty;
|
public string Key { get; init; } = string.Empty;
|
||||||
|
|||||||
@@ -0,0 +1,197 @@
|
|||||||
|
using System.Data.Common;
|
||||||
|
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||||
|
using OpenWaf.Data;
|
||||||
|
using OpenWaf.Infrastructure.Persistence;
|
||||||
|
|
||||||
|
namespace OpenWaf.Tests.Unit;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The generated query layer, checked against rendered SQL rather than against a
|
||||||
|
/// database. A wrong query should be red against a string — the same reason the
|
||||||
|
/// neighbouring deployment keeps its renderers public.
|
||||||
|
///
|
||||||
|
/// These tests also assert that the generator contributed to the build at all:
|
||||||
|
/// the metadata registration is a module initializer, and a generator that stops
|
||||||
|
/// running would otherwise show up as a failure inside the edge.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class GeneratedQueryTests
|
||||||
|
{
|
||||||
|
private const string SelectAll =
|
||||||
|
"SELECT \"Key\", \"Value\", \"UpdatedAt\" FROM \"policy_settings\"";
|
||||||
|
|
||||||
|
/// <summary>A data source that is never asked for a connection: rendering a
|
||||||
|
/// query must not need one, and this says so in the type system.</summary>
|
||||||
|
private sealed class NeverOpenedDataSource : DbDataSource
|
||||||
|
{
|
||||||
|
public override string ConnectionString { get; } = string.Empty;
|
||||||
|
|
||||||
|
protected override DbConnection CreateDbConnection() =>
|
||||||
|
throw new NotSupportedException("rendering a query must not open a connection");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static OrmContext Sqlite => new(new NeverOpenedDataSource(), SqliteDialect.Instance);
|
||||||
|
private static OrmContext Postgres => new(new NeverOpenedDataSource(), PostgresDialect.Instance);
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void The_generator_registered_the_table_it_was_given()
|
||||||
|
{
|
||||||
|
Assert.True(OrmMeta.TryGet(typeof(PolicySetting), out var meta),
|
||||||
|
"no generated metadata is registered for PolicySetting — the analyzer is not running");
|
||||||
|
|
||||||
|
Assert.Equal("policy_settings", meta.Table);
|
||||||
|
Assert.Equal(new[] { "Key", "Value", "UpdatedAt" }, meta.Columns.ToArray());
|
||||||
|
Assert.Equal("UpdatedAt", PolicySettingOrm.ColumnOf("UpdatedAt"));
|
||||||
|
Assert.Equal(string.Empty, PolicySettingOrm.ColumnOf("NotAColumn"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void A_whole_table_read_renders_the_columns_the_schema_has() =>
|
||||||
|
Assert.Equal(SelectAll, PolicySettingOrm.Query(Sqlite).RenderSelect());
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void A_captured_local_becomes_a_parameter_and_never_text_in_the_statement()
|
||||||
|
{
|
||||||
|
const string key = "streakThreshold";
|
||||||
|
var query = PolicySettingOrm.Query(Sqlite).Where(p => p.Key == key);
|
||||||
|
|
||||||
|
Assert.Equal(SelectAll + " WHERE (\"Key\" = @p0)", query.RenderSelect());
|
||||||
|
Assert.Single(query.Arguments);
|
||||||
|
Assert.Equal("streakThreshold", query.Arguments[0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void A_null_test_stays_an_is_null_and_never_becomes_an_equality_with_null()
|
||||||
|
{
|
||||||
|
// "col = NULL" is unknown rather than false: a filter written that way
|
||||||
|
// silently stops matching the rows it was written for.
|
||||||
|
var query = PolicySettingOrm.Query(Sqlite).Where(p => p.Key == "mode" && p.Value != null);
|
||||||
|
|
||||||
|
Assert.Equal(
|
||||||
|
SelectAll + " WHERE ((\"Key\" = @p0) AND (\"Value\" IS NOT NULL))",
|
||||||
|
query.RenderSelect());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void A_captured_null_is_a_null_test_too()
|
||||||
|
{
|
||||||
|
string? value = null;
|
||||||
|
var query = PolicySettingOrm.Query(Sqlite).Where(p => p.Value == value);
|
||||||
|
|
||||||
|
Assert.Equal(SelectAll + " WHERE (\"Value\" IS NULL)", query.RenderSelect());
|
||||||
|
Assert.Empty(query.Arguments);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Ordering_and_paging_render_in_the_dialects_own_grammar()
|
||||||
|
{
|
||||||
|
Assert.Equal(
|
||||||
|
SelectAll + " ORDER BY \"Key\" ASC",
|
||||||
|
PolicySettingOrm.Query(Sqlite).OrderBy(p => p.Key).RenderSelect());
|
||||||
|
|
||||||
|
Assert.Equal(
|
||||||
|
SelectAll + " ORDER BY \"UpdatedAt\" DESC LIMIT 10 OFFSET 20",
|
||||||
|
PolicySettingOrm.Query(Sqlite).OrderByDescending(p => p.UpdatedAt).Skip(20).Take(10).RenderSelect());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Count_renders_against_the_same_where_clause() =>
|
||||||
|
Assert.Equal(
|
||||||
|
"SELECT COUNT(*) FROM \"policy_settings\" WHERE (\"Key\" = @p0)",
|
||||||
|
PolicySettingOrm.Query(Sqlite).Where(p => p.Key == "mode").RenderCount());
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Both_providers_get_the_same_text_for_this_query()
|
||||||
|
{
|
||||||
|
// One SQL text for both providers is not a coincidence to lean on: it
|
||||||
|
// holds because both quote with double quotes and both bind named
|
||||||
|
// parameters. Where they differ is the dialect's job — and paging already
|
||||||
|
// differs, which is why the two tails are asserted apart.
|
||||||
|
Assert.Equal(
|
||||||
|
SelectAll + " LIMIT 2147483647 OFFSET 5",
|
||||||
|
PolicySettingOrm.Query(Postgres).Skip(5).RenderSelect());
|
||||||
|
Assert.Equal(
|
||||||
|
SelectAll + " LIMIT -1 OFFSET 5",
|
||||||
|
PolicySettingOrm.Query(Sqlite).Skip(5).RenderSelect());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void A_shape_this_layer_has_not_built_refuses_by_name()
|
||||||
|
{
|
||||||
|
var ex = Assert.Throws<UnsupportedQueryNodeException>(
|
||||||
|
() => PolicySettingOrm.Query(Sqlite).Where(p => p.Key.Length == 4));
|
||||||
|
Assert.Contains("Length", ex.What, StringComparison.Ordinal);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void A_member_that_is_not_a_column_refuses_rather_than_guessing()
|
||||||
|
{
|
||||||
|
var ex = Assert.Throws<UnsupportedQueryNodeException>(
|
||||||
|
() => PolicySettingOrm.Query(Sqlite).OrderBy(p => "not a column"));
|
||||||
|
Assert.Contains("not a column", ex.Message, StringComparison.Ordinal);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The integer a DateTimeOffset becomes on sqlite. The model puts EF's
|
||||||
|
/// <c>DateTimeOffsetToBinaryConverter</c> on every timestamp column, so that
|
||||||
|
/// encoding is the storage contract of every row this application has written;
|
||||||
|
/// the generated layer reproduces it, and this test is what makes "reproduces"
|
||||||
|
/// mean something rather than "looks plausible". It also records the resolution:
|
||||||
|
/// the encoding divides the ticks by 1000, so a round trip through the column
|
||||||
|
/// drops the sub-microsecond digits. That is EF's behaviour, not a loss added
|
||||||
|
/// here — and it is asserted, so it cannot become a surprise later.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class SqliteTimestampEncodingTests
|
||||||
|
{
|
||||||
|
private static readonly DateTimeOffset[] Instants =
|
||||||
|
[
|
||||||
|
new DateTimeOffset(2026, 10, 7, 12, 34, 56, TimeSpan.FromHours(3)),
|
||||||
|
new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero).AddTicks(123456),
|
||||||
|
new DateTimeOffset(2020, 1, 1, 0, 0, 0, TimeSpan.FromHours(-5)),
|
||||||
|
new DateTimeOffset(2024, 2, 29, 23, 59, 59, TimeSpan.FromMinutes(330)),
|
||||||
|
DateTimeOffset.MinValue,
|
||||||
|
];
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void The_encoding_this_layer_writes_is_the_one_ef_writes()
|
||||||
|
{
|
||||||
|
var efEncodes = new DateTimeOffsetToBinaryConverter().ConvertToProviderExpression.Compile();
|
||||||
|
|
||||||
|
foreach (var instant in Instants)
|
||||||
|
Assert.Equal(efEncodes(instant), Convert.ToInt64(SqliteDialect.Instance.WriteDateTimeOffset(instant)));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void What_ef_writes_this_layer_reads_back()
|
||||||
|
{
|
||||||
|
var converter = new DateTimeOffsetToBinaryConverter();
|
||||||
|
var efEncodes = converter.ConvertToProviderExpression.Compile();
|
||||||
|
|
||||||
|
foreach (var instant in Instants)
|
||||||
|
{
|
||||||
|
var stored = efEncodes(instant);
|
||||||
|
var efRead = Assert.IsAssignableFrom<DateTimeOffset>(converter.ConvertFromProvider(stored));
|
||||||
|
Assert.Equal(efRead, ReadFromStored(stored));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void The_column_has_microsecond_resolution_and_says_so()
|
||||||
|
{
|
||||||
|
var instant = new DateTimeOffset(2026, 5, 1, 0, 0, 0, TimeSpan.Zero).AddTicks(1234567);
|
||||||
|
var read = ReadFromStored(Convert.ToInt64(SqliteDialect.Instance.WriteDateTimeOffset(instant)));
|
||||||
|
|
||||||
|
Assert.Equal(new DateTimeOffset(2026, 5, 1, 0, 0, 0, TimeSpan.Zero).AddTicks(1234000), read);
|
||||||
|
Assert.NotEqual(instant.Ticks, read.Ticks);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Reads the integer the way the sqlite dialect does, without a
|
||||||
|
/// reader. The dialect's own reader path is exercised end to end by the
|
||||||
|
/// integration suite against a real database.</summary>
|
||||||
|
private static DateTimeOffset ReadFromStored(long stored)
|
||||||
|
{
|
||||||
|
var offsetMinutes = (int)(stored & 2047);
|
||||||
|
if (offsetMinutes >= 1024) offsetMinutes -= 2048;
|
||||||
|
return new DateTimeOffset((stored >> 11) * 1000, TimeSpan.FromMinutes(offsetMinutes));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,8 @@
|
|||||||
<Solution>
|
<Solution>
|
||||||
<Project Path="OpenWaf.Domain/OpenWaf.Domain.csproj" />
|
<Project Path="OpenWaf.Domain/OpenWaf.Domain.csproj" />
|
||||||
<Project Path="OpenWaf.Infrastructure/OpenWaf.Infrastructure.csproj" />
|
<Project Path="OpenWaf.Infrastructure/OpenWaf.Infrastructure.csproj" />
|
||||||
|
<Project Path="OpenWaf.Data/OpenWaf.Data.csproj" />
|
||||||
|
<Project Path="OpenWaf.Data.Generator/OpenWaf.Data.Generator.csproj" />
|
||||||
<Project Path="OpenWaf.Edge/OpenWaf.Edge.csproj" />
|
<Project Path="OpenWaf.Edge/OpenWaf.Edge.csproj" />
|
||||||
<Project Path="OpenWaf.Tests.Unit/OpenWaf.Tests.Unit.csproj" />
|
<Project Path="OpenWaf.Tests.Unit/OpenWaf.Tests.Unit.csproj" />
|
||||||
<Project Path="OpenWaf.Tests.Integration/OpenWaf.Tests.Integration.csproj" />
|
<Project Path="OpenWaf.Tests.Integration/OpenWaf.Tests.Integration.csproj" />
|
||||||
|
|||||||
@@ -44,8 +44,12 @@ printf '\n=== publish NativeAOT (%s) ===\n' "$RUNTIME"
|
|||||||
# schema step still calls three design-time APIs. Those are recorded, not hidden —
|
# schema step still calls three design-time APIs. Those are recorded, not hidden —
|
||||||
# the counts are printed below from the same log.
|
# the counts are printed below from the same log.
|
||||||
AOT_LOG=/tmp/openwaf-aot-publish.log
|
AOT_LOG=/tmp/openwaf-aot-publish.log
|
||||||
|
# OpenWafAot, not PublishAot: the latter as a command-line property is global, and
|
||||||
|
# it then reaches the referenced Roslyn analyzer (netstandard2.0) and the publish
|
||||||
|
# dies with NETSDK1207. OpenWaf.Edge.csproj turns this switch into PublishAot for
|
||||||
|
# itself only.
|
||||||
(cd dotnet && dotnet publish OpenWaf.Edge/OpenWaf.Edge.csproj -c Release -r "$RUNTIME" \
|
(cd dotnet && dotnet publish OpenWaf.Edge/OpenWaf.Edge.csproj -c Release -r "$RUNTIME" \
|
||||||
-p:PublishAot=true -p:InvariantGlobalization=true -p:DebugType=none \
|
-p:OpenWafAot=true \
|
||||||
-p:OpenWafCompiledModel=true -p:NoWarn=IL2026%3BIL3050 \
|
-p:OpenWafCompiledModel=true -p:NoWarn=IL2026%3BIL3050 \
|
||||||
-p:IlcTreatWarningsAsErrors=false) >"$AOT_LOG" 2>&1
|
-p:IlcTreatWarningsAsErrors=false) >"$AOT_LOG" 2>&1
|
||||||
publish_status=$?
|
publish_status=$?
|
||||||
|
|||||||
Reference in New Issue
Block a user