odoosearchdomain

package module
v0.0.0-...-c9154ef Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 28, 2026 License: AGPL-3.0 Imports: 6 Imported by: 4 modules, 5 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

odoosearchdomain

Go library for parsing and building Odoo search domain strings into []any structures.

import "github.com/ppreeper/odoosearchdomain"

Parsing Domains

ParseDomain takes an Odoo domain string and returns a flat []any slice where each element is either a term ([]any{field, operator, value}) or a logical connector (string).

result, err := odoosearchdomain.ParseDomain(
    "[('name', '=', 'ABC'), '|', ('phone','ilike','7620'), ('mobile', 'ilike', '7620')]",
)
// result: []any{
//   []any{"name", "=", "ABC"},
//   "|",
//   []any{"phone", "ilike", "7620"},
//   []any{"mobile", "ilike", "7620"},
// }
Supported value types
Input syntax Go type Example
'text' or "text" string ('name', '=', 'ABC')
123, -5 int ('ref', '=', 12345)
1.23, -0.5 float64 ('amount', '=', 123.45)
1e+21, 1.5e-3 float64 ('amount', '=', 1e+21) (Python's repr)
True, true bool ('active', '=', True)
False, false bool ('active', '=', False)
None, none nil ('parent_id', '=', None)
[1, 2, 3] []any ('id', 'in', [1, 2, 3])
['a', 'b'] []any ('month', 'in', ['April', 'May'])
[('field','op',val)] []any ('line', 'any', [('qty', '<=', 0)])

Both single quotes ('...') and double quotes ("...") are supported for strings. Backslash escapes are decoded the way Python's repr() encodes them: \', \", \\, \n, \t, \r, \b, \f, \v, \a, \xHH, \uHHHH, and \UHHHHHHHH. Unknown escapes (including \N{NAME}) pass through as a literal backslash plus the character, and a \x/\u/\U escape with too few hex digits is likewise kept literally. Code points outside the Unicode range, and surrogates, are rejected with ErrSyntax rather than replaced.

Integers that overflow int (Python integers are unbounded) fall back to float64.

Errors
Error Meaning
ErrSyntax Invalid token, unknown operator, or malformed domain
ErrNotEnoughAndOrTerms & or | operator missing required 2 operands
ErrNotEnoughNotTerms ! operator missing required 1 operand

Input that lacks outer [...] brackets returns an empty slice with no error. Input that begins with [ must be a well-formed domain end to end — lexer, parser, and arity errors are all reported rather than silently producing an empty result. Nested domains (values of any, child_of, and friends) are validated too. Nesting deeper than 1000 levels is rejected with ErrSyntax.

Breaking changes

These differ from earlier releases:

  • Bracketed input is no longer silently accepted when malformed. ParseDomain now returns ErrSyntax for inputs such as [1,2,3] (a plain list, not a domain) and for anything else beginning with [ that does not parse. Callers that relied on "empty slice means no filter" should treat a non-nil error as "do not run the query".
  • Fields trims whitespace and drops empty entries, so Fields("a,,b") returns ["a", "b"] rather than ["a", "", "b"].
Validation

ValidateDomain checks that a previously parsed []any slice has correct prefix-notation arity for all logical operators. It is called automatically by ParseDomain, but is also available for direct use:

terms := []any{"&", []any{"a", "=", "1"}, []any{"b", "=", "2"}}
validated, err := odoosearchdomain.ValidateDomain(terms)

Building Domains

The Domain and Term types allow programmatic construction of domain structures.

dom := odoosearchdomain.NewDomain()
dom.AddTerm("name", "=", "ABC")
dom.Or(
    odoosearchdomain.NewTerm("phone", "ilike", "7620"),
    odoosearchdomain.NewTerm("mobile", "ilike", "7620"),
)
list := dom.ToList()
// list: []any{
//   []any{"name", "=", "ABC"},
//   "|",
//   []any{"phone", "ilike", "7620"},
//   []any{"mobile", "ilike", "7620"},
// }
Domain methods
Method Description
NewDomain() *Domain Create an empty domain
AddTerm(field, op, value) Append a term
Add(term *Term) Append a pre-built term (nil is ignored)
AddConnector(op) Append a bare "&", "|", or "!" connector
And(term1, term2 *Term) Append "&" followed by two terms
Or(term1, term2 *Term) Append "|" followed by two terms
Not(term *Term) Append "!" followed by one term
Validate() error Check the built domain's operator arity
ToList() []any Serialize to a flat []any for JSON-RPC

And, Or, and Not skip the whole group when an operand is nil, so a missing term never leaves a dangling connector behind.

Utility functions
Function Description
DomainList(domains ...any) Normalize variadic domain args into []any (nothing is discarded)
DomainString(domains ...string) Normalize variadic string args into []string
Fields(field string) Split a comma-separated field list, trimming spaces

Odoo Search Domain Reference

A domain is a list of criteria, each criterion being a tuple of (field_name, operator, value) where:

field_name (str)

A field name of the current model, or a relationship traversal through a Many2one using dot-notation e.g. 'street' or 'partner_id.country'. If the field is a date(time) field, you can also specify a part of the date using 'field_name.granularity'. The supported granularities are 'year_number', 'quarter_number', 'month_number', 'iso_week_number', 'day_of_week', 'day_of_month', 'day_of_year', 'hour_number', 'minute_number', 'second_number'. They all use an integer as value.

operator (str)

An operator used to compare the field_name with the value. Valid operators are:

Operator Description
= equals to
!= not equals to
> greater than
>= greater than or equal to
< less than
<= less than or equal to
=? unset or equals to (returns true if value is either None or False, otherwise behaves like =)
=like matches field_name against the value pattern. An underscore _ in the pattern stands for (matches) any single character; a percent sign % matches any string of zero or more characters.
like matches field_name against the %value% pattern. Similar to =like but wraps value with % before matching
not like doesn't match against the %value% pattern
ilike case insensitive like
not ilike case insensitive not like
=ilike case insensitive =like
in is equal to any of the items from value, value should be a list of items
not in is unequal to all of the items from value
child_of is a child (descendant) of a value record (value can be either one item or a list of items). Takes the semantics of the model into account (i.e following the relationship field named by _parent_name).
parent_of is a parent (ascendant) of a value record (value can be either one item or a list of items). Takes the semantics of the model into account (i.e following the relationship field named by _parent_name).
any matches if any record in the relationship traversal through field_name satisfies the provided domain value.
not any matches if no record in the relationship traversal through field_name satisfies the provided domain value.
value

Variable type, must be comparable (through operator) to the named field.

Logical operators

Domain criteria can be combined using logical operators in prefix (Polish) notation:

Operator Arity Description
'&' 2 Logical AND (default between consecutive criteria)
'|' 2 Logical OR
'!' 1 Logical NOT

Mostly to negate combinations of criteria. Individual criterion generally have a negative form (e.g. = -> !=, < -> >=) which is simpler than negating the positive.

Examples

Search for partners named ABC, with a phone or mobile number containing 7620:

[('name', '=', 'ABC'), '|', ('phone','ilike','7620'), ('mobile', 'ilike', '7620')]

Search sales orders to invoice with at least one line where the product is out of stock:

[('invoice_status', '=', 'to invoice'), ('order_line', 'any', [('product_id.qty_available', '<=', 0)])]

Search for all partners born in February:

[('birthday.month_number', '=', 2)]

Nested AND with three terms:

['&', '&', ('a', '=', '1'), ('b', '=', '2'), ('c', '=', '3')]

Negate an OR combination:

['!', '|', ('active', '=', False), ('state', '=', 'draft')]

Parser Architecture

The parser uses a two-phase approach:

Phase 1 -- Lexer. A single-pass O(n) tokenizer converts the input string into a stream of typed tokens (brackets, parens, commas, quoted strings, numbers with optional decimal fraction and base-10 exponent, booleans, None). Quoted strings decode Python-style backslash escapes.

Phase 2 -- Recursive descent parser. Consumes the token stream according to this grammar. Nesting is bounded at 1000 levels to protect against stack exhaustion on hostile input:

domain  -> '[' items ']' | '[]' | '[()]'
items   -> item (',' item)*
item    -> connector | term
connector -> STRING  {where str in '&', '|', '!'}
term    -> '(' STRING ',' STRING ',' value ')'
value   -> STRING | INT | FLOAT | TRUE | FALSE | NONE | list | domain
list    -> '[' (value (',' value)*)? ']'

Nested domains in value position (for any/not any operators) are handled by peek-based disambiguation with backtracking: if the first element after [ is ( or a connector string, domain parsing is attempted first.

After parsing, a recursive prefix-notation validator checks that &/| have exactly 2 operands and ! has exactly 1 operand.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrSyntax              = errors.New("invalid syntax")
	ErrNotEnoughAndOrTerms = errors.New("not enough AND/OR terms")
	ErrNotEnoughNotTerms   = errors.New("not enough NOT terms")
)

Sentinel errors for domain parsing and validation.

Functions

func DomainList

func DomainList(domains ...any) []any

DomainList normalizes variadic domain arguments into a single []any. A single []any argument is returned as a copy; multiple arguments are returned as a slice in call order. No argument is ever discarded.

func DomainString

func DomainString(domains ...string) []string

DomainString normalizes variadic string arguments into a []string. A single empty string yields an empty slice.

func Fields

func Fields(field string) []string

Fields splits a comma-separated field list into individual field names, trimming surrounding whitespace. Empty entries are dropped.

func ParseDomain

func ParseDomain(domain string) (filter []any, err error)

ParseDomain parses an Odoo search domain string into a slice of terms and connectors.

The domain string should be formatted according to the Odoo search domain syntax:

[('field','operator',value), '|', ('field2','op2',value2), ...]

Input that is empty or lacks outer brackets is not treated as a domain and yields an empty slice with no error. Any input that begins with '[' must be a well-formed domain end to end: lexer, parser, and arity errors are all reported (ErrSyntax, ErrNotEnoughAndOrTerms, ErrNotEnoughNotTerms) rather than silently producing an empty result.

func ValidateDomain

func ValidateDomain(terms []any) (results []any, err error)

ValidateDomain checks parsed domain terms for correct AND/OR/NOT arity. Exported for backward compatibility.

Types

type Domain

type Domain []any

Domain is a programmatically built search domain. Its elements are Term values, bare connector strings ("&", "|", "!"), or raw values appended by the caller. Use ToList to serialize it to the flat []any wire format.

func NewDomain

func NewDomain() *Domain

NewDomain returns a pointer to a new, empty Domain. The builder methods use pointer receivers so they can append in place.

func (*Domain) Add

func (dom *Domain) Add(term *Term) *Domain

Add appends a pre-built term to the domain. A nil term is ignored.

func (*Domain) AddConnector

func (dom *Domain) AddConnector(operator string) *Domain

AddConnector appends a bare logical connector to the domain. Use Validate to check the finished domain; connectors are only meaningful in prefix position relative to their operands.

func (*Domain) AddTerm

func (dom *Domain) AddTerm(field, operator string, value any) *Domain

AddTerm appends a new (field, operator, value) term to the domain.

func (*Domain) And

func (dom *Domain) And(term1, term2 *Term) *Domain

And appends the "&" connector followed by the two operand terms. In prefix notation the connector must precede its operands.

func (*Domain) Not

func (dom *Domain) Not(term *Term) *Domain

Not appends the "!" connector followed by its operand term. In prefix notation the connector must precede its operand.

func (*Domain) Or

func (dom *Domain) Or(term1, term2 *Term) *Domain

Or appends the "|" connector followed by the two operand terms. In prefix notation the connector must precede its operands.

func (*Domain) ToList

func (dom *Domain) ToList() []any

ToList serializes the domain into the flat []any wire format: each Term becomes a []any tuple, and every other element (connector strings and raw values alike) is passed through unchanged — nothing is dropped. A nil domain serializes to an empty slice.

func (*Domain) Validate

func (dom *Domain) Validate() error

Validate reports whether the built domain has correct operator arity.

type Term

type Term []any

Term is a single domain criterion: (field, operator, value).

func NewTerm

func NewTerm(field, operator string, value any) *Term

NewTerm creates a new term for the given field, operator, and value.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址