Quickstart: C#
This page takes you from an AG Grid request to the parameterized SQL that answers it, in one small program. It needs no database and no driver: Craticula compiles the query and never runs it.
The packages are on NuGet. This page uses three of them:
dotnet add package Craticula.Core
dotnet add package Craticula.AgGrid
dotnet add package Craticula.Sql
Each package has its own page on nuget.org, for example Craticula.Core. The program below also lives in the repository, where the solution builds it, so this page was checked by running it from there.
What you need #
- the .NET 10 SDK;
- the repository, to run the sample as it is: clone or download https://github.com/pluries/craticula. To use the library in your own project, install the packages above instead.
Run it #
From the csharp folder of the repository:
dotnet run --project samples/Craticula.Quickstart
The program is the file below. The solution builds it, so a change to the library that breaks it breaks the build. It does five things: it declares a schema (the allowlist), takes an AG Grid request, parses it into the canonical IR, compiles it for two databases, and shows a request for an unlisted column being refused.
using Craticula.AgGrid;
using Craticula.Core.Ir;
using Craticula.Core.Schema;
using Craticula.Sql;
// 1. The schema is the allowlist: a column that is not listed here can never reach a query, and every identifier in the
// statement comes from `physical.sql.column`, never from the request.
const string schemaJson = """
{
"mode": "strict",
"source": "orders",
"stableKey": "id",
"fields": {
"id": { "type": "int64", "sortable": true, "physical": { "sql": { "column": "id" } } },
"customer": { "type": "string", "filterable": true, "sortable": true, "physical": { "sql": { "column": "customer" } } },
"amount": { "type": "decimal", "filterable": true, "sortable": true, "physical": { "sql": { "column": "amount" } } },
"status": { "type": "string", "filterable": true, "sortable": true, "physical": { "sql": { "column": "status" } } }
}
}
""";
// 2. A request exactly as AG Grid's server-side row model sends it: customers containing "acme", amount above 100,
// biggest amounts first, the first 50 rows.
const string requestJson = """
{
"startRow": 0,
"endRow": 50,
"rowGroupCols": [],
"valueCols": [],
"pivotCols": [],
"pivotMode": false,
"groupKeys": [],
"filterModel": {
"customer": { "filterType": "text", "type": "contains", "filter": "acme" },
"amount": { "filterType": "number", "type": "greaterThan", "filter": 100 }
},
"sortModel": [ { "colId": "amount", "sort": "desc" } ]
}
""";
GridSchema schema = GridSchema.Parse(schemaJson);
// 3. Parse the request into the canonical IR, then validate it against the schema and the resource limits.
AgGridParsedRequest parsed = AgGridRequestParser.Parse(requestJson, new AgGridParseOptions { Schema = schema });
FilterNode? filter = GridFilterPipeline.Process(
parsed.NativeFilter, parsed.CustomFilters, parsed.Page, schema, new ResourceLimits(), parsed.Group, parsed.Aggregations);
// 4. Compile: the same IR gives each database its own statement. Values travel as parameters, never inside the text.
foreach ((string name, ISqlDialect dialect) in new (string, ISqlDialect)[]
{
("PostgreSQL", PostgresDialect.Instance),
("SQL Server", MssqlDialect.Instance),
})
{
SqlQuery query = SqlQueryBuilder.Build(
new SqlQueryRequest { Schema = schema, Filter = filter, Sort = parsed.Sort, Page = parsed.Page }, dialect);
Console.WriteLine($"-- {name}");
Console.WriteLine(query.Sql);
Console.WriteLine($"-- parameters: {string.Join(", ", query.Parameters.Select(value => value is string text ? $"'{text}'" : value?.ToString() ?? "NULL"))}");
Console.WriteLine();
}
// 5. A column the schema does not list is refused before any query exists. Here the grid asks to filter on `password`.
const string hostileJson = """
{ "startRow": 0, "endRow": 50, "rowGroupCols": [], "valueCols": [], "pivotCols": [], "pivotMode": false, "groupKeys": [],
"filterModel": { "password": { "filterType": "text", "type": "equals", "filter": "x" } }, "sortModel": [] }
""";
try
{
AgGridParsedRequest bad = AgGridRequestParser.Parse(hostileJson, new AgGridParseOptions { Schema = schema });
GridFilterPipeline.Process(bad.NativeFilter, bad.CustomFilters, bad.Page, schema, new ResourceLimits(), bad.Group, bad.Aggregations);
Console.WriteLine("-- the unknown column was NOT refused");
}
catch (UnknownFieldException error)
{
Console.WriteLine($"-- refused: {error.GetType().Name}: {error.Message}");
}
What you should see #
The same request gives each database its own statement. Values are never part of the text: they are the parameters listed under each statement, in the order the placeholders appear. The last line shows the refusal of the column that is not in the schema.
-- PostgreSQL
SELECT * FROM "orders" WHERE ("customer" ILIKE '%' || $1 || '%' ESCAPE '\' AND "amount" > $2::numeric) ORDER BY "amount" DESC NULLS FIRST, "id" ASC NULLS LAST LIMIT $3 OFFSET $4
-- parameters: 'acme', '100', 50, 0
-- SQL Server
SELECT * FROM [orders] WHERE ([customer] COLLATE Latin1_General_CI_AS LIKE '%' + @p1 + '%' ESCAPE '\' AND [amount] > @p2) ORDER BY CASE WHEN [amount] IS NULL THEN 1 ELSE 0 END DESC, [amount] DESC, CASE WHEN [id] IS NULL THEN 1 ELSE 0 END ASC, [id] ASC OFFSET @p3 ROWS FETCH NEXT @p4 ROWS ONLY
-- parameters: 'acme', '100', 0, 50
-- refused: UnknownFieldException: Field allowlist check failed (SC-1/SC-2) for 1 colId(s): password
Read the output #
ILIKEandCOLLATE Latin1_General_CI_ASare how each database spells the default case-insensitive match (Case sensitivity); the two statements agree on which rows they return.ORDER BY "amount" DESC NULLS FIRST, "id" ASC NULLS LASTends inid, the schema's stable key, so paging is deterministic (Deterministic paging). SQL Server has noNULLS FIRST, so it spells the same order with a leadingCASE(Null ordering).- The decimal
100is printed'100'because a decimal parameter is carried as a string, so no precision is lost on the way to the driver (AR-7). Bind it as a decimal in your driver. "password"was refused because the schema lists no such column; the request never reached a compiler.
Run it on a real database #
Compile and run in one call with an execution adapter, which takes an open connection or a DbContext from you. Install the adapter you need from NuGet (Craticula.Dapper, Craticula.EntityFrameworkCore, Craticula.MongoDB.Driver or Craticula.OpenSearch.Client); each README shows its install line.
Craticula.Dapper: runs the statement on anIDbConnection, with paging, row counts and streamed CSV export.Craticula.EntityFrameworkCore: buildsIQueryableexpression trees; read its two host obligations first.- MongoDB and OpenSearch have their own compilers and clients (
Craticula.Mongo,Craticula.MongoDB.Driver,Craticula.Search,Craticula.OpenSearch.Client).
For the whole path with a browser grid, ten providers on seven database engines and a script that compares them against each other, follow the demo, or try it live on PostgreSQL and MongoDB.
Next #
- What each database needs from you before the statements are right: index and database guidance.
- The rules behind the output: semantics.
- Every setting of the schema: the GridSchema reference.