| Safe Haskell | None |
|---|---|
| Language | GHC2021 |
Hledger.Query
Description
A general query system for matching things (accounts, postings, transactions..) by various criteria, and a SimpleTextParser for query expressions.
Synopsis
- data Query
- = Any
- | None
- | Date DateSpan
- | Date2 DateSpan
- | StatusQ Status
- | Code Regexp
- | Desc Regexp
- | Tag Regexp (Maybe Regexp)
- | Acct Regexp
- | Type [AccountType]
- | Depth Int
- | DepthAcct Regexp Int
- | Real Bool
- | Amt OrdPlus Quantity (Maybe CommoditySymbol)
- | Cur Regexp
- | Change OrdPlus Quantity (Maybe CommoditySymbol)
- | Balance OrdPlus Quantity (Maybe CommoditySymbol)
- | Find Regexp (Maybe DateSpan)
- | Not Query
- | And [Query]
- | Or [Query]
- | AnyPosting [Query]
- | AllPostings [Query]
- data QueryOpt
- data OrdPlus
- payeeTag :: Maybe Text -> Either RegexError Query
- noteTag :: Maybe Text -> Either RegexError Query
- generatedTransactionTag :: Query
- parseQuery :: Day -> Text -> Either String (Query, [QueryOpt])
- parseQueryList :: Day -> [Text] -> Either String (Query, [QueryOpt])
- parseQueryTerm :: Day -> Text -> Either String (Query, [QueryOpt])
- parseAccountType :: Bool -> Text -> Either String AccountType
- parseDepthSpec :: Text -> Either RegexError DepthSpec
- parseAmountQueryArg :: String -> Text -> Either String (OrdPlus, Quantity, Maybe CommoditySymbol)
- transformQuery :: (Query -> Query) -> Query -> Query
- simplifyQuery :: Query -> Query
- filterQuery :: (Query -> Bool) -> Query -> Query
- filterQueryOrNotQuery :: (Query -> Bool) -> Query -> Query
- querySplitRowTerms :: Query -> Either String (Query, Query)
- matchesQuery :: (Query -> Bool) -> Query -> Bool
- queryIsNull :: Query -> Bool
- queryIsDate :: Query -> Bool
- queryIsDate2 :: Query -> Bool
- queryIsDateOrDate2 :: Query -> Bool
- queryIsStatus :: Query -> Bool
- queryIsCode :: Query -> Bool
- queryIsDesc :: Query -> Bool
- queryIsTag :: Query -> Bool
- queryIsAcct :: Query -> Bool
- queryIsFind :: Query -> Bool
- queryIsType :: Query -> Bool
- queryIsDepth :: Query -> Bool
- queryIsFlatDepth :: Query -> Bool
- queryIsReal :: Query -> Bool
- queryIsAmt :: Query -> Bool
- queryIsCur :: Query -> Bool
- queryIsAmtOrCur :: Query -> Bool
- queryIsChange :: Query -> Bool
- queryIsBalance :: Query -> Bool
- queryIsRowTerm :: Query -> Bool
- queryHasBalance :: Query -> Bool
- queryHasChange :: Query -> Bool
- queryIsStartDateOnly :: Bool -> Query -> Bool
- queryIsTransactionRelated :: Query -> Bool
- queryStartDate :: Bool -> Query -> Maybe Day
- queryEndDate :: Bool -> Query -> Maybe Day
- queryDateSpan :: Bool -> Query -> DateSpan
- queryDateSpan' :: Query -> DateSpan
- queryDepth :: Query -> DepthSpec
- inAccount :: [QueryOpt] -> Maybe (AccountName, Bool)
- inAccountQuery :: [QueryOpt] -> Maybe Query
- matchesTransaction :: Query -> Transaction -> Bool
- matchesTransactionExtra :: (AccountName -> Maybe AccountType) -> Query -> Transaction -> Bool
- matchesPayee :: Query -> Payee -> Bool
- matchesPosting :: Query -> Posting -> Bool
- matchesPostingExtra :: (AccountName -> Maybe AccountType) -> Query -> Posting -> Bool
- postingQueryForAccount :: (AccountName -> Maybe AccountType) -> AccountName -> Maybe AccountName -> Query -> Query
- matchesAccount :: Query -> AccountName -> Bool
- matchesAccountExtra :: (AccountName -> Maybe AccountType) -> (AccountName -> [Tag]) -> Query -> AccountName -> Bool
- matchesMixedAmount :: Query -> MixedAmount -> Bool
- matchesAmount :: Query -> Amount -> Bool
- matchesRowAmounts :: Query -> MixedAmount -> MixedAmount -> Bool
- matchesCommodity :: Query -> CommoditySymbol -> Bool
- matchesCommodityExtra :: (CommoditySymbol -> [Tag]) -> Query -> CommoditySymbol -> Bool
- matchesTag :: Query -> Tag -> Bool
- matchesPriceDirective :: Query -> PriceDirective -> Bool
- words'' :: [Text] -> Text -> [Text]
- queryprefixes :: [Text]
- tests_Query :: TestTree
Query and QueryOpt
A query is a composition of search criteria, which can be used to match postings, transactions, accounts and more.
Constructors
| Any | always match |
| None | never match data queries (in "standard" order, roughly as they appear in a transaction) |
| Date DateSpan | match primary dates in this date span |
| Date2 DateSpan | match secondary dates in this date span |
| StatusQ Status | match this txn/posting status |
| Code Regexp | match txn codes infix-matched by this regexp |
| Desc Regexp | match txn descriptions infix-matched by this regexp |
| Tag Regexp (Maybe Regexp) | match if a tag's name, and optionally its value, is infix-matched by the respective regexps |
| Acct Regexp | match account names infix-matched by this regexp |
| Type [AccountType] | match accounts whose type is one of these (or with no types, any account) |
| Depth Int | match if account depth is less than or equal to this value (or, sometimes used as a display option) |
| DepthAcct Regexp Int | match if the account matches and account depth is less than or equal to this value (usually used as a display option) |
| Real Bool | match postings with this "realness" value |
| Amt OrdPlus Quantity (Maybe CommoditySymbol) | match if the amount's numeric quantity is less thangreater thanequal to/unsignedly equal to some value, considering just amounts in this commodity if one is given |
| Cur Regexp | match if the commodity symbol is fully matched by this regexp. |
| Change OrdPlus Quantity (Maybe CommoditySymbol) | like Amt, but matching a report row (or an entry) by its change: the sum of its postings.
Not tested against postings; reports apply it after aggregating (see |
| Balance OrdPlus Quantity (Maybe CommoditySymbol) | like Amt, but matching a report row by its balance: the sum of its postings up to the end of its period.
Not tested against postings; reports apply it after aggregating (see |
| Find Regexp (Maybe DateSpan) | match if any text field (account, amount, comment, tag name or value, description, code) is infix-matched by this regexp, or if the date is within this span (present when the pattern also parses as a period expression) compound queries (expr:) |
| Not Query | negate this match |
| And [Query] | match if all of these match |
| Or [Query] | match if any of these match compound queries selecting whole transactions (any:, all:). When matching a posting, these look at the postings of its parent transaction, so a posting can be matched because of its siblings. In contexts with neither a transaction nor sibling postings available (matching an account name, a commodity symbol...), they are equivalent to And. |
| AnyPosting [Query] | match if any one posting is matched by all of these |
| AllPostings [Query] | match if all of one or more postings are matched by all of these |
A query option changes a query's/report's behaviour and output in some way.
Constructors
| QueryOptInAcctOnly AccountName | show an account register focussed on this account |
| QueryOptInAcct AccountName | as above but include sub-accounts in the account register |
| QueryOptInterval Interval | report interval extracted from a date: query | QueryOptCostBasis -- ^ show amounts converted to cost where possible | QueryOptDate2 -- ^ show secondary dates instead of primary dates |
A more expressive Ord, used for amt:, change: and balance: queries. The Abs* variants compare with the absolute value of a number, ignoring sign.
payeeTag :: Maybe Text -> Either RegexError Query Source #
Construct a query for the payee: tag
noteTag :: Maybe Text -> Either RegexError Query Source #
Construct a query for the note: tag
generatedTransactionTag :: Query Source #
Construct a query for the generated-transaction: tag
parsing
parseQuery :: Day -> Text -> Either String (Query, [QueryOpt]) Source #
A version of parseQueryList which acts on a single Text of space-separated terms.
The usual shell quoting rules are assumed. When a pattern contains whitespace, it (or the whole term including prefix) should be enclosed in single or double quotes.
A query term is either:
a search pattern, which matches on one or more fields, eg:
acct:REGEXP - match the account name with a regular expression desc:REGEXP - match the transaction description date:PERIODEXP - match the date with a period expression
The prefix indicates the field to match, or if there is no prefix account name is assumed.
a query option, which modifies the reporting behaviour in some way. There is currently one of these, which may appear only once:
inacct:FULLACCTNAME
Period expressions may contain relative dates, so a reference date is required to fully parse these.
>>>parseQuery nulldate "expenses:dining out"Right (Or [Acct (RegexpCI "expenses:dining"),Acct (RegexpCI "out")],[])
>>>parseQuery nulldate "\"expenses:dining out\""Right (Acct (RegexpCI "expenses:dining out"),[])
parseQueryList :: Day -> [Text] -> Either String (Query, [QueryOpt]) Source #
Convert a list of space-separated queries to a single query
Multiple terms are combined as follows: 1. multiple account patterns are OR'd together 2. multiple description patterns are OR'd together 3. multiple status patterns are OR'd together 4. then all terms are AND'd together
parseQueryTerm :: Day -> Text -> Either String (Query, [QueryOpt]) Source #
Parse a single query term as either a query or a query option, or return an error message if parsing fails.
parseAccountType :: Bool -> Text -> Either String AccountType Source #
Case-insensitively parse an account type's one-letter code, or if permitted, its long-form name (or another accepted spelling of that). On failure, returns the unparseable text.
parseDepthSpec :: Text -> Either RegexError DepthSpec Source #
parseAmountQueryArg :: String -> Text -> Either String (OrdPlus, Quantity, Maybe CommoditySymbol) Source #
Parse the argument of an amt:, change: or balance: query term: a comparison ([OP][SIGN]NUM,
see parseAmountQueryTerm), optionally with a commodity symbol before or after the number
(and its sign), as in >$100, >-$100, >100 EUR or >"AAPL 2026" 5.
Returns an OrdPlus, a Quantity and the commodity symbol if any,
or if parsing fails, an error message mentioning the given query type.
>>>parseAmountQueryArg "amt" ">100"Right (AbsGt,100,Nothing)>>>parseAmountQueryArg "amt" "<-$100"Right (Lt,-100,Just "$")>>>parseAmountQueryArg "change" ">= 100 EUR"Right (AbsGtEq,100,Just "EUR")>>>parseAmountQueryArg "change" "\"AAPL 2026\"+5"Right (Eq,5,Just "AAPL 2026")
modifying
transformQuery :: (Query -> Query) -> Query -> Query Source #
Bottom-up rewrite of a Query tree: recursively transform the children of each compound query (Not, And, Or, AnyPosting, AllPostings), then apply f to the resulting node. Leaf queries (Cur, Acct, Date, ...) are passed straight to f. Use this when you want to write a single-node rewrite rule and have it applied throughout the tree without re-doing the structural recursion by hand.
simplifyQuery :: Query -> Query Source #
filterQuery :: (Query -> Bool) -> Query -> Query Source #
Remove query terms (or whole sub-expressions) from this query which do not match the given predicate. XXX Semantics not completely clear. Also calls simplifyQuery on the result.
filterQueryOrNotQuery :: (Query -> Bool) -> Query -> Query Source #
Remove query terms (or whole sub-expressions) from this query which match neither the given predicate nor that predicate negated (eg, if predicate is queryIsAcct, this will keep both "acct:" and "not:acct:" terms). Also calls simplifyQuery on the result. (Since 1.24.1, might be merged into filterQuery in future.) XXX Semantics not completely clear.
querySplitRowTerms :: Query -> Either String (Query, Query) Source #
Split a query into its row terms (change: and balance: terms, including negated ones), and the rest. Row terms match report rows, after aggregation, so they must be combined with the rest of the query by AND; one used elsewhere (inside OR, a negated group, any: or all:) gives an error.
>>>querySplitRowTerms (And [Acct (toRegexCI' "a"), Not (Change AbsGt 1 Nothing)])Right (Not (Change AbsGt 1 Nothing),Acct (RegexpCI "a"))
matchesQuery :: (Query -> Bool) -> Query -> Bool Source #
Does this simple query predicate match any part of this possibly compound query ?
predicates
queryIsNull :: Query -> Bool Source #
Does this query match everything ?
queryIsDate :: Query -> Bool Source #
Is this a simple query of this type (date:) ? Does not match a compound query involving andornot. Likewise for the following functions.
queryIsDate2 :: Query -> Bool Source #
queryIsDateOrDate2 :: Query -> Bool Source #
queryIsStatus :: Query -> Bool Source #
queryIsCode :: Query -> Bool Source #
queryIsDesc :: Query -> Bool Source #
queryIsTag :: Query -> Bool Source #
queryIsAcct :: Query -> Bool Source #
queryIsFind :: Query -> Bool Source #
queryIsType :: Query -> Bool Source #
queryIsDepth :: Query -> Bool Source #
queryIsFlatDepth :: Query -> Bool Source #
Is this a flat depth limit (depth:N), applying to all accounts, rather than a per-account one (depth:REGEX=N) ?
queryIsReal :: Query -> Bool Source #
queryIsAmt :: Query -> Bool Source #
queryIsCur :: Query -> Bool Source #
queryIsAmtOrCur :: Query -> Bool Source #
queryIsChange :: Query -> Bool Source #
queryIsBalance :: Query -> Bool Source #
queryIsRowTerm :: Query -> Bool Source #
Is this a change: or balance: term (a "row term", tested against a report row's summed amounts) ?
queryHasBalance :: Query -> Bool Source #
Does this query contain a balance: term anywhere (possibly negated) ? Reports then need the postings before the report start, to know the balances.
queryHasChange :: Query -> Bool Source #
Does this query contain a change: term anywhere (possibly negated) ?
queryIsStartDateOnly :: Bool -> Query -> Bool Source #
Does this query specify a start date and nothing else (that would filter postings prior to the date) ? When the flag is true, look for a starting secondary date instead.
queryIsTransactionRelated :: Query -> Bool Source #
Does this query involve a property of transactions (or their postings), making it inapplicable to account declarations ?
accessors
queryStartDate :: Bool -> Query -> Maybe Day Source #
What start date (or secondary date) does this query specify, if any ? For OR expressions, use the earliest of the dates. NOT is ignored.
queryEndDate :: Bool -> Query -> Maybe Day Source #
What end date (or secondary date) does this query specify, if any ? For OR expressions, use the latest of the dates. NOT is ignored.
queryDateSpan :: Bool -> Query -> DateSpan Source #
What date span (or with a true argument, what secondary date span) does this query specify ? OR clauses specifying multiple spans return their union (the span enclosing all of them). AND clauses specifying multiple spans return their intersection. NOT clauses are ignored.
queryDateSpan' :: Query -> DateSpan Source #
What date span does this query specify, treating primary and secondary dates as equivalent ? OR clauses specifying multiple spans return their union (the span enclosing all of them). AND clauses specifying multiple spans return their intersection. NOT clauses are ignored.
queryDepth :: Query -> DepthSpec Source #
The depth limit this query specifies, if it has one
inAccount :: [QueryOpt] -> Maybe (AccountName, Bool) Source #
The account we are currently focussed on, if any, and whether subaccounts are included. Just looks at the first query option.
inAccountQuery :: [QueryOpt] -> Maybe Query Source #
A query for the account(s) we are currently focussed on, if any. Just looks at the first query option.
matching things with queries
matchesTransaction :: Query -> Transaction -> Bool Source #
Does the match expression match this transaction ? change:/balance: terms are ignored; reports apply them to entries' amounts (see Hledger.Reports.EntriesReport).
matchesTransactionExtra :: (AccountName -> Maybe AccountType) -> Query -> Transaction -> Bool Source #
Like matchesTransaction, but if the journal's account types are provided, any type: terms in the query must match at least one posting's account type (and any negated type: terms must match none).
matchesPayee :: Query -> Payee -> Bool Source #
Does the query match this payee ? Only payee: terms can match; any other term (a desc:, date:, acct: etc.) fails to match, since a payee on its own has no such properties.
matchesPosting :: Query -> Posting -> Bool Source #
Does the match expression match this posting ? When matching account name, and the posting has been transformed in some way, we will match either the original or transformed name.
matchesPostingExtra :: (AccountName -> Maybe AccountType) -> Query -> Posting -> Bool Source #
Like matchesPosting, but if the posting's account's type is provided, any type: terms in the query must match it (and any negated type: terms must not match it).
postingQueryForAccount :: (AccountName -> Maybe AccountType) -> AccountName -> Maybe AccountName -> Query -> Query Source #
Partially evaluate a posting query, for postings to this account
(and with this different original account name, from before aliasing or pivoting, if any).
Its account terms (acct:, type:, depth:) are decided as matchesPostingExtra would decide them,
becoming Any or None, and simplified away; the rest of the query is kept
(including any: and all: terms, which test sibling postings, and find: terms).
So for any posting p with these account names,
matchesPostingExtra atype (postingQueryForAccount atype a morig q) p == matchesPostingExtra atype q p.
This lets the account terms be tested once per account, rather than once per posting;
checking assert rules uses it this way (see Hledger.Data.JournalChecks.Assert).
matchesAccount :: Query -> AccountName -> Bool Source #
Does the query match this account name ? Only acct: and depth: terms can match; any other term (a date:, desc: etc.) fails to match, since an account name on its own has no such properties. (For matching type: and tag: terms against an account's other data, see matchesAccountExtra.)
matchesAccountExtra :: (AccountName -> Maybe AccountType) -> (AccountName -> [Tag]) -> Query -> AccountName -> Bool Source #
Like matchesAccount, but with optional extra matching features:
- If the account's type is provided, any type: terms in the query must match it (and any negated type: terms must not match it).
- If the account's tags are provided, any tag: terms must match at least one of them (and any negated tag: terms must match none).
matchesMixedAmount :: Query -> MixedAmount -> Bool Source #
Does the query match this mixed amount ? It does if it matches any of the (single-commodity) amounts in it, or for an empty mixed amount, a zero amount.
matchesAmount :: Query -> Amount -> Bool Source #
Does the match expression match this (simple) amount ?
matchesRowAmounts :: Query -> MixedAmount -> MixedAmount -> Bool Source #
Do the change: and balance: terms of this query match a report row (or an entry)
with this change and this balance ? Each term matches like an amt: term does
(see matchesMixedAmount): if any commodity's total amount, or with a commodity symbol,
that commodity's total, passes the comparison. Costs are ignored, so amounts in one
commodity at different costs are combined (they are kept apart in a MixedAmount).
Other kinds of query term are ignored.
matchesCommodity :: Query -> CommoditySymbol -> Bool Source #
matchesCommodityExtra :: (CommoditySymbol -> [Tag]) -> Query -> CommoditySymbol -> Bool Source #
Like matchesCommodity, but also supporting Tag queries, using the provided function to look up a commodity's tags.
matchesTag :: Query -> Tag -> Bool Source #
Does the query match the name and optionally the value of this tag ? Non-tag: query terms are ignored (this might disrupt some boolean queries).
matchesPriceDirective :: Query -> PriceDirective -> Bool Source #
Does the query match this market price ?
words'' :: [Text] -> Text -> [Text] Source #
Quote-and-prefix-aware version of words - don't split on spaces which are inside quotes, including quotes which may have one of the specified prefixes in front, and maybe an additional not: prefix in front of that.
queryprefixes :: [Text] Source #