Calling methods and deleting from data files (<function>, <delete>, CSV)
Status: loading is in place. The reader checks the files (see Data files);
this page is about what the loader does with <function>, <delete> and CSV files, and how a method opts
in to being called from a data file.
Methods a data file may call
Section titled “Methods a data file may call”Odoo lets a <function> call any attribute of a model. ERPForAll lets it call only methods that say so
(ADR 0009 §8): a method is data-callable when it carries #[data_callable] or #[rpc(effect = …)]
(every RPC method is data-callable). Nothing else can be reached from a data file, so an addon that is
only read cannot call a private helper that skips an access check.
# erp_sdk::addon!(name = "library");use erp_sdk::prelude::*;
#[model(name = "library.book", description = "Book")]pub struct Book { #[field(char, required)] pub name: Option<Arc<str>>, #[field(integer)] pub copies: i32,}
#[methods(Book)]impl Book { /// Called as `<function model="library.book" name="restock"><value eval="[ref('book_a')]"/>…`. /// A records method: the first argument of the `<function>` is the ids. #[method] #[data_callable] async fn restock(this: &RecordSet<Book>, tx: &mut Transaction, count: i64) -> Result<bool> { for book in this.iter() { let copies = i64::from(book.get(tx, Book::COPIES).await?); let total = i32::try_from(copies + count) .map_err(|_| Error::validation("too many copies"))?; book.set(tx, Book::COPIES, total).await?; } Ok(true) }
/// A model method (Odoo's `@api.model`): no ids. #[method] #[data_callable(model)] async fn seed(this: &RecordSet<Book>, tx: &mut Transaction, name: String) -> Result<RecordSet<Book>> { this.create(tx, vec![this.vals().set(Book::NAME, name.as_str())]).await }
/// Private by name, still callable from data (Odoo calls such methods from data files too); /// the `_` prefix keeps it out of RPC, which needs `#[rpc]`. #[method] #[data_callable(model)] async fn _migrate(_this: &RecordSet<Book>, _tx: &mut Transaction) -> Result<bool> { Ok(true) }
/// Not declared: a `<function>` naming it fails the load. #[method] async fn recount(_this: &RecordSet<Book>, _tx: &mut Transaction) -> Result<bool> { Ok(true) }}# fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {# erp_testkit::Harness::builder([&ADDON]).check()?;# Ok(())# }#[data_callable] takes model for a model method, like #[rpc]. It has no effect class: a <function>
runs inside the module operation’s transaction, and effects belong to the RPC transport. A method may carry
#[rpc(hide)] and #[data_callable] together; #[rpc(hide)] only removes RPC. A method with
#[rpc(effect = …)] must not also carry #[data_callable] (it already is). A chain of overrides is
data-callable when any implementation along it declares the level; the oldest declaration’s parameter
table and binder are used, as for RPC.
Mistakes the compiler catches
Section titled “Mistakes the compiler catches”Both #[rpc(effect = …)] and #[data_callable] on one method:
# erp_sdk::addon!(name = "library");# use erp_sdk::prelude::*;# #[model(name = "library.book", description = "Book")]# pub struct Book {}#[methods(Book)]impl Book { #[method] #[rpc(effect = read)] #[data_callable] async fn total(this: &RecordSet<Book>, tx: &mut Transaction) -> Result<i64> { Ok(0) }}# fn main() {}An unknown parameter, or a reserved parameter name (ids and context are keys of the call):
# erp_sdk::addon!(name = "library");# use erp_sdk::prelude::*;# #[model(name = "library.book", description = "Book")]# pub struct Book {}#[methods(Book)]impl Book { #[method] #[data_callable(records)] async fn total(this: &RecordSet<Book>, tx: &mut Transaction) -> Result<i64> { Ok(0) }}# fn main() {}# erp_sdk::addon!(name = "library");# use erp_sdk::prelude::*;# #[model(name = "library.book", description = "Book")]# pub struct Book {}#[methods(Book)]impl Book { #[method] #[data_callable] async fn total(this: &RecordSet<Book>, tx: &mut Transaction, context: i64) -> Result<i64> { Ok(context) }}# fn main() {}Arguments
Section titled “Arguments”<function model="library.book" name="seed" eval="['Dune']"/>
<function model="library.book" name="restock"> <value eval="[ref('book_a'), ref('book_b')]"/> <!-- the ids --> <value type="int">5</value> <!-- count --></function>
<function model="library.book" name="restock" uid="base.user_admin" context="{'tracking_disable': True}"> <value eval="ref('book_a')"/> <value name="count" eval="3"/> <value name="context" eval="{'lang': 'fr_FR'}"/> <!-- merged into the call's context --></function>- Positional arguments come from
eval(a list or tuple) or from the<value>and nested<function>children in order;<value name="…">gives a keyword.evaland children cannot be mixed (the reader refuses it, as Odoo’s schema does). - They bind to the method’s parameters in declaration order, keywords by name, with the typed conversion
of RPC arguments (an
i64parameter takes an integer, not"5"). Failures are load errors:takes 1 positional argument but 2 were given,got an unexpected keyword argument 'x',got multiple values for argument 'x',missing a required argument: 'x',argument 'count': expected an integer, got string. - A records method takes the ids first: a list (falsy ids dropped), or one id. A model method takes none.
- A nested
<function>runs first and its result is the argument; a recordset result is its ids. uidandcontexton the<function>(or an enclosing element) set the acting user and the context, as for<record>. Acontextkeyword is merged into that context and is not passed on.- A method’s own error stops the load with its kind (a
Validationerror stays one). - Under
noupdate(the element or an enclosing<data noupdate="1">) a<function>runs on install and is skipped on upgrade. Method names with__are refused by the reader.
<delete>
Section titled “<delete>”<delete model="library.book" id="book_old"/><delete model="library.book" search="[('copies', '=', 0)]"/>It runs in every mode, also under noupdate. The records are the search result, or the record of the
external id, in one unlink. An id that does not exist, or whose record is already gone, is not an
error: the load goes on and returns a DeleteTargetMissing notice in OperationOutcome::data_notices.
Two differences from Odoo, both toward failing loudly (ADR 0018): a search that does not evaluate or does
not run fails the load (Odoo logs a warning and deletes only the id target), and an id that belongs to
a record of another model than model is refused (Odoo would unlink whichever record of model has that
number).
CSV files
Section titled “CSV files”A CSV file is loaded through the importer (load() with the id column), so a row with an existing
external id updates its record and a new one creates it. The model is the file name up to the first -
(res.partner-extra.csv loads into res.partner). The context carries mode (init or update),
module, noupdate and the install_* keys, and never lang. If any message of the importer is an
error, the install stops with all the messages:
Module loading library failed: file data/library.book.csv could not be processed:No matching record found for external id 'nope' in field 'Author'On upgrade, a file without an id column is not loaded (it could only create duplicates): the operation
goes on and returns a SkippedFile notice with the reason. One2many lines declaring their own external ids
(field/id) are lifted to their own ir.model.data entries in the same load session; subsequent imports update
the existing child records.