Repository navigation
Database Query Translation
Celly.Json.Query translates safe, user-authored CEL filter expressions into parameterized database queries for JSON documents — with zero database driver dependencies and full NativeAOT compatibility.
dotnet add package Celly.Json.Query| Target | Translator / Dialect | Output |
|---|---|---|
| Azure Cosmos DB (NoSQL) | CelQueryDialects.Cosmos |
Parameterized Cosmos SQL (WHERE + Parameters) |
PostgreSQL (jsonb) |
CelQueryDialects.PostgresJsonb |
Parameterized PostgreSQL jsonb SQL |
SQL Server 2022+ (JSON / NVARCHAR) |
CelQueryDialects.SqlServer |
Parameterized JSON_VALUE / OPENJSON SQL |
SQLite (json1) |
CelQueryDialects.Sqlite |
Parameterized json_extract / json_each SQL |
| MongoDB | MongoFilterTranslator |
MongoDB Extended JSON filter document |
EF Core / IQueryable<T> (LINQ) |
CelLinqExpressionTranslator / .WhereCel(...)
|
Strongly-typed Expression<Func<T, bool>> (EF Core, ToJson(), Cosmos/Mongo LINQ, LINQ-to-Objects) |
| Custom SQL Dialect | Implement ICelQueryDialect
|
Any JSON-capable SQL database |
All literal values are automatically extracted into parameters (@p0, @p1, ...) to prevent SQL injection:
using Celly.Json.Query;
// Azure Cosmos DB
CelSqlQuery cosmos = CelSqlQueryTranslator.Translate(
"user.age >= 18 && 'admin' in user.roles && items.exists(i, i.price >= 50)",
CelQueryDialects.Cosmos,
rootSource: "c");
// cosmos.ToSelectSql("c") ->
// SELECT * FROM c WHERE (((c.user.age >= @p0) AND ARRAY_CONTAINS(c.user.roles, @p1))
// AND EXISTS(SELECT VALUE _e0 FROM _e0 IN c.items WHERE (_e0.price >= @p2)))
// cosmos.Parameters -> [(@p0, 18), (@p1, "admin"), (@p2, 50)]Swap only the dialect and column name:
CelSqlQuery pg = CelSqlQueryTranslator.Translate(expr, CelQueryDialects.PostgresJsonb, rootSource: "doc");
CelSqlQuery mssql = CelSqlQueryTranslator.Translate(expr, CelQueryDialects.SqlServer, rootSource: "doc");
CelSqlQuery sqlite = CelSqlQueryTranslator.Translate(expr, CelQueryDialects.Sqlite, rootSource: "doc");In PostgresJsonbDialect, homogeneous constant in [...] list literals (such as tier in ['pro', 'enterprise'] or age in [18, 25, 32]) are translated to a single typed array parameter (= ANY(@p0) with string[], long[], double[], or bool[]) for better PostgreSQL query-plan caching and fewer parameters.
Pass a schema-backed CelEnv to Translate(...) to validate field paths and resolve ambiguous functions (size(string) vs. size(array), 'k' in map vs. v in array) before hitting your database:
CelEnv env = JsonSchemaEnv.Create(orderSchema);
CelSqlQuery query = CelSqlQueryTranslator.Translate("size(name) > 3 && size(roles) >= 1", CelQueryDialects.Cosmos, env);string filterJson = MongoFilterTranslator.Translate(
"user.age >= 18 && 'admin' in user.roles && items.exists(i, i.price >= 50)");
// {"\$and":[{"\$and":[{"user.age":{"\$gte":18}},{"user.roles":"admin"}]},{"items":{"\$elemMatch":{"price":{"\$gte":50}}}}]}Pass filterJson directly to new JsonFilterDefinition<BsonDocument>(filterJson) in MongoDB.Driver (or any MongoDB client).
Translate CEL expressions into strongly-typed Expression<Func<T, bool>> trees with zero ORM dependencies — works with EF Core (relational tables, navigation collections, and OwnsOne(...).ToJson() JSON columns), Cosmos LINQ, MongoDB LINQ, Marten, and LINQ-to-Objects:
using Celly.Json.Query;
// Extension methods on any IQueryable<T> (AIP-160 style filtering + sorting)
var matchingOrders = await dbContext.Orders
.WhereCel("user.age >= 18 && user.active && items.exists(i, i.price >= 50 && i.qty > 0)")
.OrderByCel("total desc, user.age asc")
.ToListAsync();
// Or chain OrderByDescendingCel / ThenByCel / ThenByDescendingCel:
var sorted = dbContext.Orders
.OrderByDescendingCel("total")
.ThenByCel("user.name");
// SQL ORDER BY translation pairs with CelSqlQuery.ToSelectSql:
string orderBySql = CelSqlQueryTranslator.TranslateOrderBy("user.age desc, user.name asc", CelQueryDialects.PostgresJsonb, env, rootSource: "doc");
string fullSql = pg.ToSelectSql("docs", "id", orderBySql);
// Or get the compiled Expression<Func<Order, bool>> directly:
Expression<Func<Order, bool>> predicate =
CelLinqExpressionTranslator.Translate<Order>("tier in ['pro', 'enterprise'] && total >= 100");- Property binding checks
CelLinqMapping<T>first, then[CelPropertyName](skipping[CelIgnore]), then[JsonPropertyName], then case-insensitive CLR property names. - Automatically aligns CEL literals with C#
int,decimal,double,Enum(by string name or numeric value),Guid,DateTime,DateTimeOffset,DateOnly,TimeOnly,timestamp(...), andNullable<T>properties so EF Core generates index-friendly SQL. - Annotated with
[RequiresUnreferencedCode]/[RequiresDynamicCode]soCelSqlQueryTranslatorandMongoFilterTranslatorremain 100% NativeAOT-clean.
When exposing CEL filters or sorting directly to API callers, decouple your public CEL field names from your internal entity/document schema and bound query complexity:
// Strongly-typed LINQ mapper (flattening, computed expressions, strict allowlist)
var map = new CelLinqMapping<OrderEntity>(allowUnmapped: false)
.Map("customerName", o => o.Customer.FullName)
.Map("billing.amount", o => o.Total)
.Map("itemCount", o => o.Items.Count);
// AST safety policy (works across LINQ, SQL, and MongoDB translators)
var policy = new CelQueryPolicy
{
MaxAstDepth = 12,
MaxInListSize = 50,
MaxComprehensionDepth = 1,
DeniedFields = new HashSet<string> { "passwordHash", "internal" },
};
var orders = await dbContext.Orders
.WhereCel("customerName == 'Alice' && itemCount >= 2", policy: policy, mapping: map)
.OrderByCel("itemCount desc", policy: policy, mapping: map)
.ToListAsync();For CelSqlQueryTranslator and MongoFilterTranslator, pass a CelFieldMapping(allowUnmapped: false) (supports exact path and prefix remapping, 100% NativeAOT-safe) alongside CelQueryPolicy:
var fieldMap = new CelFieldMapping(allowUnmapped: false)
.Map("customerName", "user.full_name")
.Map("customer", "user");
CelSqlQuery pg = CelSqlQueryTranslator.Translate(
"customerName == 'Alice' && customer.age >= 18",
CelQueryDialects.PostgresJsonb,
rootSource: "doc",
policy: policy,
mapping: fieldMap);For simple model-level renames or hiding sensitive properties without affecting JSON serialization, annotate CLR properties directly with [CelPropertyName] and [CelIgnore]:
public sealed class AccountEntity
{
[CelPropertyName("handle")]
[JsonPropertyName("user_name")]
public string UserName { get; set; } = string.Empty;
[CelIgnore]
public string PasswordHash { get; set; } = string.Empty;
}
// Queries "handle" -> AccountEntity.UserName; referencing "passwordHash" throws CelQueryTranslationException.
var results = dbContext.Accounts.WhereCel("handle == 'ada'").ToList();In CelLinqExpressionTranslator, resolution follows this exact precedence order:
-
CelQueryPolicy— validated first against the raw CEL AST before any mapping or binding. -
CelLinqMapping<T>— checked before reflection/attributes; an explicit.Map(...)always wins (even over[CelIgnore]or[CelPropertyName]). WhenallowUnmapped: false, unmapped fields fail here. -
[CelIgnore]— excludes the property from automatic reflection binding. -
[CelPropertyName("...")]— exact ordinal match. -
[JsonPropertyName("...")]— exact ordinal match. - CLR property name — case-insensitive fallback.
Celly.Json — High-performance System.Text.Json adapter for Celly (.NET 10, NativeAOT-ready, MIT License).