Query AST: saving a search and running it later
Status: implemented. A saved search, a dashboard tile, an export or an agent tool describes its query
as one JSON document, the query AST. Any code can parse it, check its shape, store its
canonical text, and later run it as whoever is running it, with that person’s rights. The decision
is ADR 0045, the behaviour is docs/specs/orm/query-ast.md (SPEC-QAST), the design is
docs/design/m3-qast.md.
Odoo keeps saved filters as three Python-literal text columns and applies them with the rights of whoever opens them; nothing checks them until they run, and nothing bounds them. The AST keeps the second part (it always runs as the person who runs it) and fixes the rest: a versioned format, one canonical form, strict parsing, limits, a check against the current registry at every run.
The document
Section titled “The document”A document is a JSON object with a version, a kind (search_read or read_group), a model, a
domain, an optional context, an order and a page. Every object has a closed set of keys: an
unknown key is an error, never ignored.
{"version": 1, "kind": "search_read", "model": "account.move", "domain": [["state", "=", "posted"], ["invoice_user_id", "=", {"param": "uid"}]], "fields": ["name", "amount_total"], "order": [{"field": "invoice_date", "dir": "desc"}], "limit": 80}{"version": 1, "kind": "read_group", "model": "account.move", "groupby": [{"path": "invoice_date", "granularity": "month"}], "aggregates": [{"func": "count"}, {"func": "sum", "field": "amount_total"}], "having": [{"aggregate": "amount_total:sum", "op": ">", "value": 1000}], "order": [{"key": "amount_total:sum", "dir": "desc"}], "limit": 500}limitis required: 1 to 2,000 rows forsearch_read, 1 to 10,000 groups forread_group. A larger value is an error, not a cap.offset(default 0) is at most 1,000,000.fieldsis a non-empty list: there is no “all fields”, because “all” changes meaning when the registry changes.domainis Odoo’s list syntax. A value can be a principal parameter,{"param": "uid"}, which stands for the person who runs the query:uid,company_id,company_ids,todayornow. The document never holds a user id or a company of its own.contexttakes one key,active_test(a boolean).lang,tzandallowed_company_idscome from the running environment, as they do for a live call; any other key is refused.- In a
read_groupdocument,orderandhavingname a group-by (invoice_date:month) or an aggregate (__count,amount_total:sum) declared in the same document.array_agg,array_agg_distinctandrecordsetaggregates (unbounded output per group) are refused.
Build it in Rust
Section titled “Build it in Rust”use erp_sdk::Granularity;use erp_sdk::query::{AggregateFunc, OrderDir, QueryAst, QueryLimits};
let limits = QueryLimits::default();
let ast = QueryAst::read_group("account.move") .group_by("invoice_date", Some(Granularity::Month)) .count() .aggregate("amount_total", AggregateFunc::Sum) .order("amount_total:sum", OrderDir::Desc, None) .limit(500) .build(&limits)?;assert_eq!(ast.limit(), 500);# Ok::<(), erp_sdk::query::QueryAstError>(())The builder’s domain(...) takes an erp_sdk::query::Json tree of the list syntax. A builder collects the same document the parser reads and runs the same validation in build, so
a built AST and a parsed one accept and refuse the same things. A mistake is a QueryAstError
with the path of the element: query AST $.model: invalid model name 'Bad Model': ....
Parse, store, compare
Section titled “Parse, store, compare”use erp_sdk::query::{QueryAst, QueryLimits};
let limits = QueryLimits::default();let ast = QueryAst::parse( br#"{"version": 1, "kind": "search_read", "model": "res.partner", "fields": ["name"], "limit": 20, "order": [{"field": "name"}]}"#, &limits,)?;
// The canonical form: sorted keys, no spaces, every key written. Store it as `text`.let canonical = ast.canonical();assert!(canonical.starts_with(br#"{"context":{},"domain":[],"fields":["name"]"#));
// It parses back to an equal query, and writes the same bytes again.let again = QueryAst::parse(&canonical, &limits)?;assert_eq!(again, ast);assert_eq!(again.canonical(), canonical);# Ok::<(), erp_sdk::query::QueryAstError>(())Two documents that differ only in key order or in absent keys versus their defaults are the same
query and have the same canonical bytes. Hash the canonical bytes if you need an identity. Store
them as text, not jsonb: jsonb rewrites numbers and drops duplicate keys.
QueryAst::parse takes bytes. A layer that already holds a parsed JSON tree
(erp_fields::json::parse) passes it to QueryAst::from_json. Paging gives a new validated
query: ast.with_page(limit, offset, &limits).
Limits
Section titled “Limits”QueryLimits::default() holds the ceilings: 64 KiB of input, JSON depth 32, 512 domain conditions,
domain depth 16, 128 fields, 6 group-bys, 32 aggregates, 8 order terms, 32 having conditions,
4 path segments. A host can lower any of them and never raise or disable them:
use erp_sdk::query::QueryLimits;
let limits = QueryLimits::builder().max_rows(100).build()?;// 0 and values above the default are errors, not "unlimited"assert!(QueryLimits::builder().max_rows(0).build().is_err());assert!(QueryLimits::builder().max_rows(5000).build().is_err());# let _ = limits;# Ok::<(), erp_sdk::query::QueryAstError>(())Run it
Section titled “Run it”erp_sdk::query::run(tx, &env, &ast) checks the query against the transaction’s registry and the
environment’s access, then runs it through Records::search_read or Records::read_group: the
same statement, the same method chain, the same errors as the live call. check does the checks
and fetches nothing.
use erp_sdk::prelude::*;use erp_sdk::query::{QueryAst, QueryLimits, QueryResult, check, run};
async fn replay(tx: &mut Transaction, stored: &[u8]) -> Result<()> { // the text was checked when it was stored and is read again now, under the same limits let ast = QueryAst::parse(stored, &QueryLimits::default())?; let env = tx.env(); // the person running it: nobody else's rights are involved
// does the query still fit the registry and this person's access? (no data statement) check(tx, &env, &ast).await?;
match run(tx, &env, &ast).await? { QueryResult::Rows { rows, truncated } => { println!("{} rows; more rows exist: {truncated}", rows.len()); } QueryResult::Groups { columns, rows, truncated } => { println!("{columns:?}: {} groups; more exist: {truncated}", rows.len()); } _ => {} } Ok(())}# fn main() {}- No superuser mode.
checkandrunrefuse an environment in superuser mode (sudo(), theSystemprincipal) with anAccesserror: a favourite saved by anyone must not read every record. Audited elevated replay is planned. - The environment decides everything. The document carries no user. A query saved by an
administrator and run by a clerk uses the clerk’s model access, record rules, field groups and
company scope;
{"param": "uid"}is the clerk’s id. Nothing is remembered between runs: no compiled statement, no “this query was valid” flag. - A field the person cannot read, or that no longer exists, fails the run with an error that
names it (
AccessorValidation). The query never runs with the field left out: a droppedfieldsentry would change what a report means, a dropped domain condition would broaden it. truncatedis true when more rows or groups matched than the query’slimit. The ORM fetcheslimit + 1in the same statement to know.checkfollows the planning half of the coderunuses. For plain conditions it sends no data statement;child_of/parent_ofandaccessconditions are resolved through the database, socheckmay send statements for them. It does not call#[method(override)]implementations of_read_group;rundoes.- Stable pages. A grouped run adds the group-bys your
orderdoes not name, ascending, after your terms, so groups tied on an aggregate keep one order andoffsetpaging does not repeat or skip groups. - Time. A query is bounded in size, not in running time. Run it under the host’s
statement_timeout(the HTTP server will set one per request); 2,000 rows of heavy x2many or computed fields cost what they cost.
Errors
Section titled “Errors”| Error | Kind | When |
|---|---|---|
QueryAstError | Validation | the document is refused: path and reason (query AST $.limit: limit is 2001; at most 2000 allowed) |
| unknown or abstract model, unknown field, bad granularity | Validation | the registry no longer fits the document |
| no read access to the model, an unreadable field | Access | the running principal’s rights |
erp_fields::Error::from(query_ast_error) gives the Validation error with the original as its
source, so ? works in functions that return the shared Result.
What is not here
Section titled “What is not here”The storage of saved queries and their UI, turning a natural-language question into a document, the RPC method and tool that run a document, the JSON Schema of the format and scheduled runs are all planned.