外观
haystack
原文: https://finproducts.atlassian.net/wiki/spaces/JIDD3/pages/34793423094/FIN+5.3.1+haystack 中文整理基于 FIN 5.3.1
导读: Haystack 模型和客户端 API
以下为 API 参考,保留英文以便对照源码;目录已列出(英文标题便于检索);概述已尽量中译。
目录(导读)
- mixins
- classes
- enums
- facets
- errs
- Slot Details
- defVal
- equals
- hash
- make
- mime
- toStr
- meta
- remoteTrace
- about
- call
- close
- commit
- eval
- open
- read
- readAll
- readById
- readByIds
- uri
- compare
- dis
- name
- dist
- fromStr
- lat
- lng
- readGrid
- delimiter
- flush
- newline
- showHeader
- stripUnits
- writeGrid
- contains
- day
- eachDay
- eachMonth
- end
- isDay
- isMonth
- isQuarter
- isRange
- isWeek
- isYear
- lastMonth
- lastQuarter
- lastWeek
- lastYear
- makeMonth
- makeWeek
- makeYear
- minus
- month
- next
- numDays
- pastMonth
- pastWeek
- pastYear
- period
- plus
- prev
- quarter
- range
- start
- thisMonth
- thisQuarter
- thisWeek
- thisYear
- toCode
- toSpan
- today
- week
- year
- yesterday
- symbol
- _id
- each
- eachWhile
- get
- has
- id
- isEmpty
- map
- missing
- trap
- addArg
- compareDis
- dict0
- dict1
- dict2
- dict3
- dict4
- dict5
- dict6
- dictAll
- dictAny
- dictEq
- dictFindAll
- dictHashKey
- dictMap
- dictMerge
- dictNames
- dictRemove
- dictRemoveAll
- dictRename
- dictSet
- dictToDis
- dictToHaystack
- dictToMap
- dictVals
- dictsNames
- discretePeriods
- emptyDict
- escapeTagName
- …(其余标题见英文正文)
API 正文(英文)
| TypedDict | TypedDict wraps a dict that maps tags to statically typed fields. | | XStr | XStr is an extended string which is a type name and value encoded as a string. | | ZincReader | Read Haystack data in Zinc format. | | ZincWriter | Write Haystack data in Zinc format. |
enums
| SpanMode | SpanMode enumerates relative or absolute span modes |
facets
| TypedTag | Facet to annotate a TypedDict field. |
errs
| CallErr | CallErr is raised when a server returns an error grid from a client call to a REST operation. |
| DependErr | DependErr indicates a missing dependency |
| DisabledErr | DisabledErr indicates access of a disabled resource. |
| DownErr | DownErr indicates a communications or networking problem |
| FaultErr | FaultErr indicates a software or configuration problem |
| UnitErr | UnitErr indicates an operation between two incompatible units |
| UnknownNameErr | UnknownNameErr is thrown when Dict.trap or Grid.col fails to resolve a name. |
| UnknownRecErr | UnknownKindErr when a Kind cannot be resolved or parsed |
| ValidateErr | ValidateErr when a validation fails. |
Bin
@Js const class Bin : Obj
Bin is a tag value for a binary file stored on disk rather than in the in-memory record database. The Bin instance itself stores the MIME type.
Constructors
| make | Construct with mime type string. |
Fields
| defVal | Bin for "text/plain; charset=utf-8". |
| mime | MimeType of the bin file. |
Methods
| equals | |
| hash | |
| toStr |
Slot Details
defVal
const static Bin defVal := utf-8")
Bin for "text/plain; charset=utf-8".
equals
virtual override Bool equals(Obj? that)
hash
virtual override Int hash()
make
static new make(Str mime)
Construct with mime type string.
mime
const MimeType mime
MimeType of the bin file.
toStr
virtual override Str toStr()
CallErr
@Js const class CallErr : Err
CallErr is raised when a server returns an error grid from a client call to a REST operation.
Fields
| meta | Grid.meta from the error grid response |
| remoteTrace | Remote stack trace if available |
Slot Details
meta
const Dict meta
Grid.meta from the error grid response
remoteTrace
const Str? remoteTrace
Remote stack trace if available
Client
class Client : Obj
Client manages a network connection to a haystack server.
Fields
| uri | URI of endpoint such as "http://host/api/myProj/". |
Methods
| about | Call "about" operation to query server summary info. |
| call | Call the given REST operation with its request grid and return the response grid. |
| close | Close the session by sending the close op. |
| commit | Commit a set of diffs. |
| eval | Evaluate an Axon expression and return results as Grid. |
| open | Open with URI of project such as "http://host/api/myProj/". |
| read | Call "read" operation to read a record that matches the given filter. |
| readAll | Call "read" operation to read a record all recs which match the given filter. |
| readById | Call "read" operation to read a record by its identifier. |
| readByIds | Call "read" operation to read a list of records by their identifiers. |
| toStr | Return uri.toStr |
Slot Details
about
Dict about()
Call "about" operation to query server summary info. Also see HTTP API.
call
Grid call(Str op, Grid? req := null, Bool checked := true)
Call the given REST operation with its request grid and return the response grid. If req is null, then an empty grid used for request. If the checked flag is true and server returns an error grid, then raise CallErr, otherwise return the grid itself.
close
Void close()
Close the session by sending the close op.
commit
Grid commit(Grid req)
Commit a set of diffs. The req parameter must be a grid with a "commit" tag in the grid.meta. The rows are the items to commit. Return result as Grid or or raise CallErr if server returns error grid.
Also see HTTP API.
Examples:
// add new record
tags := ["site":Marker.val, "dis":"Example Site"])
toCommit := Etc.makeDictGrid(["commit":"add"], tags)
client.commit(toCommit)
// update dis tag
changes := ["id": orig->id, "mod":orig->mod, "dis": "New dis"]
toCommit := Etc.makeDictGrid(["commit":"update"], changes)
client.commit(toCommit)eval
Grid eval(Str expr)
Evaluate an Axon expression and return results as Grid. Raise CallErr if server returns error grid. Also see HTTP API.
open
static Client open(Uri uri, Str username, Str password, [Str:Obj]? opts := null)
Open with URI of project such as "http://host/api/myProj/". Throw IOErr for network/connection error or AuthErr if credentials are not authenticated.
read
Dict? read(Str filter, Bool checked := true)
Call "read" operation to read a record that matches the given filter. If there is more than one record, then it is undefined which one is returned. If there are no matches then return null or raise UnknownRecException based on checked flag. Raise CallErr if server returns error grid. Also see HTTP API.
readAll
Grid readAll(Str filter)
Call "read" operation to read a record all recs which match the given filter. Raise CallErr if server returns error grid. Also see HTTP API.
readById
Dict? readById(Obj id, Bool checked := true)
Call "read" operation to read a record by its identifier. If the record is not found then return null or raise UnknownRecException based on checked flag. Raise CallErr if server returns error grid. Also see HTTP API.
readByIds
Grid readByIds(Obj[] ids, Bool checked := true)
Call "read" operation to read a list of records by their identifiers. Return a grid where each row of the grid maps to the respective id list (indexes line up). If checked is true and any one of the ids cannot be resolved then raise UnknownRecErr for first id not resolved. If checked is false, then each id not found has a row where every cell is null. Raise CallErr if server returns error grid. Also see HTTP API.
toStr
virtual override Str toStr()
Return uri.toStr
uri
const Uri uri
URI of endpoint such as "http://host/api/myProj/". This URI always ends in a trailing slash.
Col
@Js abstract const class Col : Obj
Column of a Grid
Methods
| compare | Compare based on name |
| dis | Display name for columm which is meta.dis(null, name) |
| equals | Equality is based on reference |
| meta | Meta-data for column |
| name | Programatic name identifier for columm |
| toStr | String representation is name |
Slot Details
compare
override Int compare(Obj x)
Compare based on name
dis
Str dis()
Display name for columm which is meta.dis(null, name)
equals
override Bool equals(Obj? that)
Equality is based on reference
meta
abstract Dict meta()
Meta-data for column
name
abstract Str name()
Programatic name identifier for columm
toStr
override Str toStr()
String representation is name
Coord
@Js @Serializable { simple=true } const class Coord : Obj
Geographic coordinate as latitude and longitute in decimal degrees.
Constructors
| fromStr | Decode from string formatted as "C(lat,lng)" |
| make | Construct from floating point decimal degrees |
Fields
| defVal | Default value is "C(0.0,0.0)" |
Methods
| dist | Compute great-circle distance two coordinates using haversine forumula. |
| equals | Equality is based on lat/lng |
| hash | Hash is based on lat/lng |
| lat | Latitude in decimal degrees |
| lng | Longtitude in decimal degrees |
| toStr | Represented as "C(lat,lng)" |
Slot Details
defVal
const static Coord defVal := ...
Default value is "C(0.0,0.0)"
dist
Float dist(Coord c2)
Compute great-circle distance two coordinates using haversine forumula.
equals
virtual override Bool equals(Obj? that)
Equality is based on lat/lng
fromStr
static new fromStr(Str s, Bool checked := true)
Decode from string formatted as "C(lat,lng)"
hash
virtual override Int hash()
Hash is based on lat/lng
lat
Float lat()
Latitude in decimal degrees
lng
Float lng()
Longtitude in decimal degrees
make
new make(Float lat, Float lng)
Construct from floating point decimal degrees
toStr
virtual override Str toStr()
Represented as "C(lat,lng)"
CsvReader
@Js class CsvReader : Obj
Read Haystack data in CSV format.
Constructors
| make | Wrap input stream |
Methods
| readGrid | Return CSV file as a grid. |
Slot Details
make
new make(InStream in)
Wrap input stream
readGrid
virtual override Grid readGrid()
Return CSV file as a grid. Invalid column names are automatically converted in safe names, but the original name may be retreived from the col meta via the "orig" tag.
CsvWriter
@Js class CsvWriter : Obj
Write Haystack data in CSV format.
Constructors
| make | Wrap output stream |
Fields
| delimiter | Delimiter character; defaults to comma. |
| newline | Newline string; defaults to "\n" |
| showHeader | Include the column names as a header row |
| stripUnits | Strip units from all numbers |
Methods
| close | Close the underlying output stream |
| flush | Flush the underlying output stream and return this |
| writeGrid | Write grid as CSV and return this |
Slot Details
close
Bool close()
Close the underlying output stream
delimiter
Int delimiter := 44
Delimiter character; defaults to comma.
flush
This flush()
Flush the underlying output stream and return this
make
new make(OutStream out, Dict? opts := null)
Wrap output stream
newline
Str newline := "\n"
Newline string; defaults to "\n"
showHeader
Bool showHeader := true
Include the column names as a header row
stripUnits
Bool stripUnits := false
Strip units from all numbers
writeGrid
virtual override This writeGrid(Grid grid)
Write grid as CSV and return this
DateSpan
@Js @Serializable { simple=true } const class DateSpan : Obj
DateSpan models a span of time between two dates.
Constructors
| fromStr | Construct DateSpan from Str. |
| make | Construct a new DateSpan using a start date and period, or an explicit start date and end date. |
Fields
| day | Constant for a day period. |
| end | Inclusive end date for this span. |
| month | Constant for a month period. |
| numDays | Get number of days in this span. |
| period | The period: day, week, month, quarter, year, or range. |
| quarter | Constant for a quarter period. |
| range | Constant for an arbitrary period. |
| start | Start date for this span. |
| week | Constant for a week period. |
| year | Constant for a month period. |
Methods
| contains | Does this span inclusively contain the given Date inclusively |
| dis | Return display name for this span. |
| eachDay | Iterate each day in this DateSpan. |
| eachMonth | Iterate each month in this date range as a range of first to last day in each month. |
| equals | Objects are equal if start, end, and period match. |
| hash | Hash is based on start/end/period. |
| isDay | Convenience for period == DateSpan.day |
| isMonth | Convenience for period == DateSpan.month |
| isQuarter | Convenience for period == DateSpan.quarter |
| isRange | Convenience for period == DateSpan.range |
| isWeek | Convenience for period == DateSpan.week |
| isYear | Convenience for period == DateSpan.year |
| lastMonth | Construct for month previous to this month 1..28-31 |
| lastQuarter | DateSpan for 3 month quarter previous to this quarter |
| lastWeek | Construct for week previous to this week sun..sat (uses locale start of week) |
| lastYear | Construct for year previous to this year Jan-1..Dec-31 |
| makeMonth | Convenience for make(Date(year, month, 1), DateSpan.month). |
| makeWeek | Convenience for make(start, DateSpan.week). |
| makeYear | Convenience for make(Date(year, Month.jan, 1), DateSpan.year). |
| minus | Shift start and end by the given number of days. |
| next | Return the next DateSpan based on the period |
| pastMonth | Construct for last 30days today-30days..today |
| pastWeek | Construct for last 7 days as today-7days..today |
| pastYear | Construct for this past today-365days..today |
| plus | Shift start and end by the given number of days. |
| prev | Return the previous DateSpan based on the period |
| thisMonth | Construct for this month as 1..28-31 |
| thisQuarter | DateSpan for this 3 month quarter |
| thisWeek | Construct for this week as sun..sat (uses locale start of week) |
| thisYear | Construct for this year Jan-1..Dec-31 |
| toCode | Return axon representation for this span. |
| toSpan | Convert this instance to a Span instance |
| toStr | Str representation is "<start>,<end |
| today | Convenience for make(Date.today). |
| yesterday | Convenience for make(Date.today-1day). |
Slot Details
contains
Bool contains(Date? val)
Does this span inclusively contain the given Date inclusively
day
const static Str day := "day"
Constant for a day period.
dis
Str dis(Bool explicit := false)
Return display name for this span. If explicit is true, display actual dates, as opposed to Today or Yesterday.
eachDay
Void eachDay(|Date,Int| func)
Iterate each day in this DateSpan.
eachMonth
Void eachMonth(|DateSpan| f)
Iterate each month in this date range as a range of first to last day in each month.
end
const Date end
Inclusive end date for this span.
equals
virtual override Bool equals(Obj? obj)
Objects are equal if start, end, and period match.
fromStr
static new fromStr(Str s, Bool checked := true)
Construct DateSpan from Str. This method supports parsing from the following formats:
- "<start>,<period>"
- "<start>,<end>"
- "today", "yesterday"
- "thisWeek", "thisMonth", "thisYear"
- "pastWeek", "pastMonth", "pastYear"
- "lastWeek", "lastMonth", "lastYear"
Where <start> and <end> are YYYY-MM-DD date formats and period is "day", "week", "month", or "year".
hash
virtual override Int hash()
Hash is based on start/end/period.
isDay
Bool isDay()
Convenience for period == DateSpan.day
isMonth
Bool isMonth()
Convenience for period == DateSpan.month
isQuarter
Bool isQuarter()
Convenience for period == DateSpan.quarter
isRange
Bool isRange()
Convenience for period == DateSpan.range
isWeek
Bool isWeek()
Convenience for period == DateSpan.week
isYear
Bool isYear()
Convenience for period == DateSpan.year
lastMonth
static DateSpan lastMonth()
Construct for month previous to this month 1..28-31
lastQuarter
static DateSpan lastQuarter()
DateSpan for 3 month quarter previous to this quarter
lastWeek
static DateSpan lastWeek()
Construct for week previous to this week sun..sat (uses locale start of week)
lastYear
static DateSpan lastYear()
Construct for year previous to this year Jan-1..Dec-31
make
new make(Date start := Date.today(), Obj endOrPer := DateSpan.day)
Construct a new DateSpan using a start date and period, or an explicit start date and end date. If a period of week, month, quarter, or year is used, then the start date will be adjusted, if necessary, to the first of week, first of month, first of quarter, or first of year, respectively. If a date is passed as end, then the period is implicitly range.
makeMonth
static DateSpan makeMonth(Int year, Month month)
Convenience for make(Date(year, month, 1), DateSpan.month).
makeWeek
static DateSpan makeWeek(Date start)
Convenience for make(start, DateSpan.week).
makeYear
static DateSpan makeYear(Int year)
Convenience for make(Date(year, Month.jan, 1), DateSpan.year).
minus
@Operator DateSpan minus(Duration d)
Shift start and end by the given number of days.
month
const static Str month := "month"
Constant for a month period.
next
DateSpan next()
Return the next DateSpan based on the period:
- day: next day
- week: next week
- month: next month
- year: next year
- range: roll start/end forward one day
numDays
const Int numDays
Get number of days in this span.
pastMonth
static DateSpan pastMonth()
Construct for last 30days today-30days..today
pastWeek
static DateSpan pastWeek()
Construct for last 7 days as today-7days..today
pastYear
static DateSpan pastYear()
Construct for this past today-365days..today
period
const Str period
The period: day, week, month, quarter, year, or range.
plus
@Operator DateSpan plus(Duration d)
Shift start and end by the given number of days.
prev
DateSpan prev()
Return the previous DateSpan based on the period:
- day: previous day
- week: previous week
- month: previous month
- quarter: previous quarter
- year: previous year
- range: roll start/end back one day
quarter
const static Str quarter := "quarter"
Constant for a quarter period.
range
const static Str range := "range"
Constant for an arbitrary period.
start
const Date start
Start date for this span.
thisMonth
static DateSpan thisMonth()
Construct for this month as 1..28-31
thisQuarter
static DateSpan thisQuarter()
DateSpan for this 3 month quarter
thisWeek
static DateSpan thisWeek()
Construct for this week as sun..sat (uses locale start of week)
thisYear
static DateSpan thisYear()
Construct for this year Jan-1..Dec-31
toCode
Str toCode()
Return axon representation for this span.
toSpan
Span toSpan(TimeZone tz)
Convert this instance to a Span instance
toStr
virtual override Str toStr()
Str representation is "<start>,<end|period>".
today
static DateSpan today()
Convenience for make(Date.today).
week
const static Str week := "week"
Constant for a week period.
year
const static Str year := "year"
Constant for a month period.
yesterday
static DateSpan yesterday()
Convenience for make(Date.today-1day).
Def
@Js const mixin Def : Dict
Def models a definition dictionary
Methods
| name | Return simple name of definition |
| symbol | Symbolic identifier for this definition |
Slot Details
name
abstract Str name()
Return simple name of definition
symbol
abstract Symbol symbol()
Symbolic identifier for this definition
DependErr
@Js const class DependErr : Err
DependErr indicates a missing dependency
Constructors
| make | Construct with message and optional cause. |
Slot Details
make
new make(Str? msg, Err? cause := null)
Construct with message and optional cause.
Dict
@Js const mixin Dict : Dict
Dict is a map of name/value pairs. It is used to model grid rows, grid meta-data, and name/value object literals. Dict is characterized by:
- names must match
Etc.isTagNamerules - values should be one valid Haystack kinds
- get
[]access returns null if name not found - trap
->access throws exception if name not found
Also see Etc.emptyDict, Etc.makeDict.
Methods
| _id | Temp shim until we break backward compatibility |
| dis | Get display string for dict or the given tag. |
| each | Iterate through the name/value pairs |
| eachWhile | Iterate through the name/value pairs until the given function returns non-null, then break the iteration and return resulting object. |
| get | Get the value for the given name or def if name not mapped |
| has | Return true if the given name is mapped to a non-null value. |
| id | Get the id tag as a Ref or raise CastErr/UnknownNameErr |
| isEmpty | Return if the there are no name/value pairs |
| map | Create a new instance of this dict with the same names, but apply the specified closure to generate new values. |
| missing | Return true if the given name is not mapped to a non-null value. |
| toStr | Return string for debugging only |
| trap | Get the value mapped by the given name. |
Slot Details
_id
virtual override Ref _id()
Temp shim until we break backward compatibility
dis
virtual Str? dis(Str? name := null, Str? def := "")
Get display string for dict or the given tag. If name is null, then return display text for the entire dict using Etc.dictToDis. If name is non-null then format the tag value using its appropiate toLocale method. If name is not defined by this dict, then return def.
each
abstract override Void each(|Obj,Str| f)
Iterate through the name/value pairs
eachWhile
abstract override Obj? eachWhile(|Obj,Str->Obj?| f)
Iterate through the name/value pairs until the given function returns non-null, then break the iteration and return resulting object. Return null if function returns null for every name/value pair.
get
@Operator abstract override Obj? get(Str name, Obj? def := null)
Get the value for the given name or def if name not mapped
has
abstract override Bool has(Str name)
Return true if the given name is mapped to a non-null value.
id
virtual Ref id()
Get the id tag as a Ref or raise CastErr/UnknownNameErr
isEmpty
abstract override Bool isEmpty()
Return if the there are no name/value pairs
map
virtual override This map(|Obj,Str->Obj| f)
Create a new instance of this dict with the same names, but apply the specified closure to generate new values.
missing
abstract override Bool missing(Str name)
Return true if the given name is not mapped to a non-null value.
toStr
virtual override Str toStr()
Return string for debugging only
trap
abstract override Obj? trap(Str name, Obj?[]? args := null)
Get the value mapped by the given name. If it is not mapped to a non-null value, then throw an UnknownNameErr.
DisabledErr
const class DisabledErr : Err
DisabledErr indicates access of a disabled resource.
Constructors
| make |
Slot Details
make
new make(Str? msg, Err? cause := null)
DownErr
@Js const class DownErr : Err
DownErr indicates a communications or networking problem
Constructors
| make | Construct with message and optional cause |
Slot Details
make
new make(Str msg, Err? cause := null)
Construct with message and optional cause
Etc
@Js const class Etc : Obj
Etc is the utility methods for Haystack.
Methods
| addArg | |
| compareDis | Given two display strings, return 1, 0, or -1 if a is less than, equal to, or greater than b. |
| dict0 | Empty dict singleton |
| dict1 | Create a Dict with one non-nullable name/value pair |
| dict2 | Create a Dict with two non-nullable name/value pairs |
| dict3 | Create a Dict with three non-nullable name/value pairs |
| dict4 | Create a Dict with four non-nullable name/value pairs |
| dict5 | Create a Dict with five non-nullable name/value pairs |
| dict6 | Create a Dict with six non-nullable name/value pairs |
| dictAll | Return if all of the tag name/value pairs match the given function. |
| dictAny | Return if any of the tag name/value pairs match the given function. |
| dictEq | Return if two dicts are equal with same name/value pairs. |
| dictFindAll | Return a new Dict containing the name/value pairs for which f returns true. |
| dictHashKey | Construct an object which wraps a dict and is suitable to use for a hash key in a Map. |
| dictMap | Apply the given map function to each name/value pair to construct a new Dict. |
| dictMerge | Add/set all the name/value pairs in a with those defined in b. |
| dictNames | Get a read/write list of the dict's name keys. |
| dictRemove | Remove a name/val pair from an exisiting dict, or if the name isn't found then return original dict. |
| dictRemoveAll | Remove all names from the given dict. |
| dictRename | Rename given name if its defined in the dict, otherwise return original. |
| dictSet | Set a name/val pair in an existing dict or if dict is null then create a new dict with given name/val pair. |
| dictToDis | Given a dict, attempt to find the best display string |
| dictToHaystack | Coerce dict to Haystack types, see toHaystack. |
| dictToMap | Convert a Dict to a read/write map. |
| dictVals | Get all the non-null values mapped by a dictionary. |
| dictsNames | Given a list of dictionaries, find all the common names used. |
| discretePeriods | Iterate a discrete period string formatted in base64. |
| emptyDict | Get the emtpy Dict instance. |
| escapeTagName | Escape tag name into "__{utf-8 hex}" format |
| gridFlatten | Flatten a list of grids into a single grid. |
| isEscapedTagName | Return if tag name starts with "__" as escaped name |
| isKindName | Return if the given string is a legal kind name |
| isTagName | Return if the given string is a legal tag name |
| macro | Process macro pattern with given scope of variable name/value pairs. |
| macroVars | Return the list of variable tag names used in the given macro pattern. |
| makeDict | Make a Dict instance where val is one of the following |
| makeDict1 | Make a Dict with one name/value pair. |
| makeDict2 | Make a Dict with two name/value pairs. |
| makeDict3 | Make a Dict with three name/value pairs. |
| makeDict4 | Make a Dict with four name/value pairs. |
| makeDict5 | Make a Dict with five name/value pairs. |
| makeDict6 | Make a Dict with six name/value pairs. |
| makeDictGrid | Construct a grid for a Dict row. |
| makeDicts | Make a list of Dict instances using makeDict. |
| makeDictsGrid | Construct a grid for a list of Dict rows. |
| makeEmptyGrid | Construct an empty grid with just the given grid level meta-data. |
| makeErrGrid | Construct a grid for an error response. |
| makeListGrid | Construct a grid with one column for a list. |
| makeListsGrid | Construct a grid for a list of rows, where each row is a list of cells. |
| makeMapGrid | Convenience for makeDictGrid |
| makeMapsGrid | Convenience for makeDictsGrid |
| relDis | Get a relative display name. |
| tagToLocale | Get the localized string for the given tag name for the current locale. |
| toDateSpan | Coerce an object to a DateSpan |
| toErrMeta | Map an exception to its standard tags |
| toGrid | Coerce a value to a Grid |
| toHaystack | Coerce a value to one of the Haystack types. |
| toId | Coerce a value to a Ref identifier |
| toIds | Coerce a value to a list of Ref identifiers |
| toRec | Coerce a value to a record Dict |
| toRecs | Coerce a value to a list of record Dicts |
| toSpan | Coerce an object to a Span with optional timezone |
| toTagName | Take an arbitrary string and convert into a safe tag name. |
| unescapeTagName | Unescape tag name from "__{utf-8 hex}" format |
Slot Details
addArg
static Void addArg(StrBuf b, Str name, Obj? arg)
compareDis
static Int compareDis(Str a, Str b)
Given two display strings, return 1, 0, or -1 if a is less than, equal to, or greater than b. The comparison is case insensitive and takes into account trailing digits so that a dis str such as "Foo-10" is greater than "Foo-2".
dict0
static Dict dict0()
Empty dict singleton
dict1
static Dict dict1(Str n, Obj v)
Create a Dict with one non-nullable name/value pair
dict2
static Dict dict2(Str n0, Obj v0, Str n1, Obj v1)
Create a Dict with two non-nullable name/value pairs
dict3
static Dict dict3(Str n0, Obj v0, Str n1, Obj v1, Str n2, Obj v2)
Create a Dict with three non-nullable name/value pairs
dict4
static Dict dict4(Str n0, Obj v0, Str n1, Obj v1, Str n2, Obj v2, Str n3, Obj v3)
Create a Dict with four non-nullable name/value pairs
dict5
static Dict dict5(Str n0, Obj v0, Str n1, Obj v1, Str n2, Obj v2, Str n3, Obj v3, Str n4, Obj v4)
Create a Dict with five non-nullable name/value pairs
dict6
static Dict dict6(Str n0, Obj v0, Str n1, Obj v1, Str n2, Obj v2, Str n3, Obj v3, Str n4, Obj v4, Str n5, Obj v5)
Create a Dict with six non-nullable name/value pairs
dictAll
static Bool dictAll(Dict d, |Obj?,Str->Bool| f)
Return if all of the tag name/value pairs match the given function.
dictAny
static Bool dictAny(Dict d, |Obj?,Str->Bool| f)
Return if any of the tag name/value pairs match the given function.
dictEq
static Bool dictEq(Dict a, Dict b)
Return if two dicts are equal with same name/value pairs. Value are compared via the Obj.equals method. Ordering of the dict tags is not considered.
dictFindAll
static Dict dictFindAll(Dict d, |Obj?,Str->Bool| f)
Return a new Dict containing the name/value pairs for which f returns true. If f returns false for every pair, then return an empty Dict.
dictHashKey
static Obj dictHashKey(Dict d)
Construct an object which wraps a dict and is suitable to use for a hash key in a Map. The key provides implementations of Obj.hash and Obj.equals based on the the name/value pairs in the dict. Hash keys do not support Dicts which contain anything but scalar values (nested lists, dicts, and grids are silently ignored for hash/equality purposes).
dictMap
static Dict dictMap(Dict d, |Obj?,Str->Obj?| f)
Apply the given map function to each name/value pair to construct a new Dict. NOTE: use Dict.map now
dictMerge
static Dict dictMerge(Dict a, Obj? b)
Add/set all the name/value pairs in a with those defined in b. If b defines a remove value then that name/value is removed from a. The b parameter may be any value accepted by makeDict
dictNames
static Str[] dictNames(Dict d)
Get a read/write list of the dict's name keys.
dictRemove
static Dict dictRemove(Dict d, Str name)
Remove a name/val pair from an exisiting dict, or if the name isn't found then return original dict.
dictRemoveAll
static Dict dictRemoveAll(Dict d, Str[] names)
Remove all names from the given dict. Ignore any name not defined as a tag.
dictRename
static Dict dictRename(Dict d, Str oldName, Str newName)
Rename given name if its defined in the dict, otherwise return original.
dictSet
static Dict dictSet(Dict? d, Str name, Obj? val)
Set a name/val pair in an existing dict or if dict is null then create a new dict with given name/val pair. If val is null this is semantically equivalent to dictRemove(d, name).
dictToDis
static Str? dictToDis(Dict dict, Str? def := "")
Given a dict, attempt to find the best display string:
distagdisMacrotag returnsmacrousing dict as scopedisKeymaps to qname locale keynametagtagtagidtag- default
dictToHaystack
static Dict dictToHaystack(Dict dict, Dict? opts := null)
Coerce dict to Haystack types, see toHaystack.
dictToMap
static Str:Obj? dictToMap(Dict? d)
Convert a Dict to a read/write map. This method is expensive, when possible you should instead use Dict.each.
dictVals
static Obj[] dictVals(Dict d)
Get all the non-null values mapped by a dictionary.
dictsNames
static Str[] dictsNames(Dict?[] dicts)
Given a list of dictionaries, find all the common names used. Return the names in standard sorted order. Any null dicts are skipped.
discretePeriods
static Void discretePeriods(Str str, |Int,Int| f)
Iterate a discrete period string formatted in base64. Call the iterator function for each period where time is offset in minutes from base timestamp and dur is duration of period in minutes (assuming a minutely interval). This method may also be used discreteEnumPeriods() in which case the dur parameter will be the enum ordinal.
emptyDict
static Dict emptyDict()
Get the emtpy Dict instance.
escapeTagName
static Str escapeTagName(Str n)
Escape tag name into "__{utf-8 hex}" format
gridFlatten
static Grid gridFlatten(Grid[] grids)
Flatten a list of grids into a single grid. Each grid's rows are appended to a single grid in the order passed. The resulting grid columns will be the intersection of all the individual grid columns. Grid meta and column merged together.
isEscapedTagName
static Bool isEscapedTagName(Str n)
Return if tag name starts with "__" as escaped name
isKindName
static Bool isKindName(Str n)
Return if the given string is a legal kind name:
- first char must be ASCII upper case letter:
a-z - rest of chars must be ASCII letter or digit:
a-z,A-Z,0-9, or_
isTagName
static Bool isTagName(Str n)
Return if the given string is a legal tag name:
- first char must be ASCII lower case letter or underbar:
a-zor_ - rest of chars must be ASCII letter,digit, or underbar:
a-z,A-Z,0-9, or_ - if first char is underbar, then it must have a at least one additional alpha-num character
- or if first two chars are underbar, then must be followed by a hexdecimal characters for a UTF-8 encoded string
macro
static Str macro(Str pattern, Dict scope)
Process macro pattern with given scope of variable name/value pairs. The pattern is a Unicode string with embedded expressions:
$tag: resolve tag name from scope, variable name ends with first non-tag character, seeEtc.isTagName${tag}: resolve tag name from scope$<pod::key>: localization key
Any variables which cannot be resolved in the scope are returned as-is (such $name) in the result string.
If a tag resolves to Ref, then we use Ref.dis for string.
macroVars
static Str[] macroVars(Str pattern)
Return the list of variable tag names used in the given macro pattern. This includes "$tag" and "${tag}" variables, but does not include "$pod::key" localization keys.
makeDict
static Dict makeDict(Obj? val)
Make a Dict instance where val is one of the following:
- Dict: return
val - null: return
emptyDict - Str:Obj?: wrap map as Dict
- Str[]: dictionary of key/Marker value pairs
makeDict1
@Deprecated { msg="Use dict1" } static Dict makeDict1(Str n, Obj? v)
Make a Dict with one name/value pair. Backward compatibility only for nullable values, use dict1 now.
makeDict2
@Deprecated { msg="Use dict2" } static Dict makeDict2(Str n0, Obj? v0, Str n1, Obj? v1)
Make a Dict with two name/value pairs. Backward compatibility only for nullable values, use dict2 now.
makeDict3
@Deprecated { msg="Use dict3" } static Dict makeDict3(Str n0, Obj? v0, Str n1, Obj? v1, Str n2, Obj? v2)
Make a Dict with three name/value pairs. Backward compatibility only for nullable values, use dict3 now.
makeDict4
@Deprecated { msg="Use dict4" } static Dict makeDict4(Str n0, Obj? v0, Str n1, Obj? v1, Str n2, Obj? v2, Str n3, Obj? v3)
Make a Dict with four name/value pairs. Backward compatibility only for nullable values, use dict4 now.
makeDict5
@Deprecated { msg="Use dict5" } static Dict makeDict5(Str n0, Obj? v0, Str n1, Obj? v1, Str n2, Obj? v2, Str n3, Obj? v3, Str n4, Obj? v4)
Make a Dict with five name/value pairs. Backward compatibility only for nullable values, use dict5 now.
makeDict6
@Deprecated { msg="Use dict6" } static Dict makeDict6(Str n0, Obj? v0, Str n1, Obj? v1, Str n2, Obj? v2, Str n3, Obj? v3, Str n4, Obj? v4, Str n5, Obj? v5)
Make a Dict with six name/value pairs. Backward compatibility only for nullable values, use dict6 now.
makeDictGrid
static Grid makeDictGrid(Obj? meta, Dict row)
Construct a grid for a Dict row. The meta parameter can be any makeDict value.
makeDicts
static Dict[] makeDicts(Obj?[] maps)
Make a list of Dict instances using makeDict.
makeDictsGrid
static Grid makeDictsGrid(Obj? meta, Dict?[] rows)
Construct a grid for a list of Dict rows. The meta parameter can be any makeDict value. Any null dicts result in an empty row of all nulls. If no non-null rows, then return makeEmptyGrid.
makeEmptyGrid
static Grid makeEmptyGrid(Obj? meta := null)
Construct an empty grid with just the given grid level meta-data. The meta parameter can be any makeDict value.
makeErrGrid
static Grid makeErrGrid(Err e, Obj? meta := null)
Construct a grid for an error response.
makeListGrid
static Grid makeListGrid(Obj? meta, Str colName, Obj? colMeta, Obj?[] rows)
Construct a grid with one column for a list. The meta and colMeta parameters can be any makeDict value.
makeListsGrid
static Grid makeListsGrid(Obj? meta, Str[] colNames, Obj?[]? colMetas, Obj?[][] rows)
Construct a grid for a list of rows, where each row is a list of cells. The meta and colMetas parameters can be any makeDict value.
makeMapGrid
static Grid makeMapGrid(Obj? meta, Str:Obj? row)
Convenience for makeDictGrid
makeMapsGrid
static Grid makeMapsGrid(Obj? meta, Str:Obj?[] rows)
Convenience for makeDictsGrid
relDis
static Str relDis(Str parent, Str child)
Get a relative display name. If the child display name starts with the parent, then we can strip that as the common suffix.
tagToLocale
static Str tagToLocale(Str name)
Get the localized string for the given tag name for the current locale. See Localization.
toDateSpan
static DateSpan toDateSpan(Obj? val, HaystackContext? cx := null)
Coerce an object to a DateSpan:
Func: function which evaluates to date range (must be run in a context)DateSpan: return itselfDate: one day rangeSpan: returnSpan.toDateSpanStr: evaluates toDateSpan.fromStrDate..Date: starting and ending date (inclusive)Date..Number: starting date and num of days (day unit required)DateTime..DateTime: use starting/ending dates; if end is midnight, then use previous dateNumber: convert as year
toErrMeta
static Dict toErrMeta(Err e)
Map an exception to its standard tags:
dis: error display stringerr: markererrTrace: Str stack dumpaxonTrace: Axon stack dump (if applicable)errType: exception type qname
toGrid
static Grid toGrid(Obj? val, Dict? meta := null)
Coerce a value to a Grid:
- if grid just return it
- if row in grid of size, return row.grid
- if scalar return 1x1 grid
- if dict return grid where dict is only
- if list of dict return grid where each dict is row
- if list of non-dicts, return one col grid with rows for each item
- if non-zinc type return grid with cols val, type
toHaystack
static Obj? toHaystack(Obj? val, Dict? opts := null)
Coerce a value to one of the Haystack types. Recursively coerce dicts and lists. This method does not support grids. Options:
- checked: marker to throw err for non-haystack values; coerce otherwise
toId
static Ref toId(Obj? val)
Coerce a value to a Ref identifier:
- Ref returns itself
- Row or Dict, return
idtag - Grid return first row id
toIds
static Ref[] toIds(Obj? val)
Coerce a value to a list of Ref identifiers:
- Ref returns itself as list of one
- Ref[] returns itself
- Dict return
idtag - Dict[] return
idtags - Grid return
idcolumn
toRec
static Dict toRec(Obj? val, HaystackContext? cx := null)
Coerce a value to a record Dict:
- Row or Dict returns itself
- Grid returns first row (must have at least one row)
- List returns first item (must have at least one item which is Ref or Dict)
- Ref will make a call to read database (must be run in a context)
toRecs
static Dict[] toRecs(Obj? val, HaystackContext? cx := null)
Coerce a value to a list of record Dicts:
- null return empty list
- Ref or Ref[] will read database (must be run in a context)
- Row or Row[] returns itself
- Dict or Dict[] returns itself
- Grid is mapped to list of rows
toSpan
static Span toSpan(Obj? val, TimeZone? tz := null, HaystackContext? cx := null)
Coerce an object to a Span with optional timezone:
Span: return itselfSpan+tz: update timezone using same dates only if aligned to midnightStr: returnSpan.fromStrusing current timezoneStr+tz: returnSpan.fromStrusing given timezoneDateTime..DateTime: range of two DateTimesDate..DateTime: start day for date until the end timestampDateTime..Date: start timestamp to end of day for end dateDateTime: span of a single timestampDateSpan: anything accepted bytoDateSpanin current timezoneDateSpan+tz: anything accepted bytoDateSpanusing given timezone
toTagName
static Str toTagName(Str n)
Take an arbitrary string and convert into a safe tag name. Do not assume any specific conversion algorithm as it might change in the future. The empty string is not supported.
unescapeTagName
static Str unescapeTagName(Str n)
Unescape tag name from "__{utf-8 hex}" format
FaultErr
@Js const class FaultErr : Err
FaultErr indicates a software or configuration problem
Constructors
| make | Construct with message and optional cause |
Slot Details
make
new make(Str msg, Err? cause := null)
Construct with message and optional cause
Filter
@Js abstract const class Filter : Obj
Filter models a declarative predicate for selecting dicts. See Filters for details.
Constructors
| fromStr | Parse a query from string - see Filters for format. |
Methods
| equals | Equality is based on the normalized string. |
| hash | Hash is based on toStr. |
| matches | Return if the specified record matches this filter. |
| toStr | Return the normalized string of the filter |
Slot Details
equals
virtual override Bool equals(Obj? that)
Equality is based on the normalized string.
fromStr
static new fromStr(Str s, Bool checked := true)
Parse a query from string - see Filters for format. If the query cannot be parsed then return null or throw ParseErr with location of error.
hash
virtual override Int hash()
Hash is based on toStr.
matches
Bool matches(Dict r, HaystackContext? cx := null)
Return if the specified record matches this filter. Pass a context object to enable def aware features and to path through refs via the -> operator.
toStr
abstract override Str toStr()
Return the normalized string of the filter
Grid
@Js const mixin Grid
Two dimensional tabular data structure composed of Cols and Rows. Grids may be created by factory methods on Etc or using GridBuilder. See docHaystack.
Methods
| addCol | Return a new grid with an additional column. |
| addColMeta | Return a new grid with additional column meta-data. |
| addCols | Return a new grid by adding the given grid as a new set of columns to this grid. |
| addMeta | Return a new grid with additional grid level meta-data. |
| all | Return true if the function returns true for all of the rows in the grid. |
| any | Return true if the function returns true for any of the rows in the grid. |
| col | Get a column by its name. |
| colDisNames | Convenience for cols mapped to Col.dis. |
| colNames | Convenience for cols mapped to Col.name. |
| colToList | Get a column as a list of the cell values ordered by row. |
| cols | Columns |
| colsToLocale | Return a new Grid wich each col name mapped to its localized tag name if the col does not already have a display string. |
| commit | Return a new Grid which is the result of applying the given diffs to this grid. |
| each | Iterate the rows |
| eachWhile | Iterate every row until the function returns non-null. |
| filter | Return a new grid which finds matching rows based on the given filter. |
| find | Find one matching row or return null if no matches. |
| findAll | Return a new grid which finds matching the rows in this grid. |
| findIndex | Find one matching row index or return null if no matches. |
| first | Get the first row or return null if grid is empty. |
| flatMap | Return a new grid which maps each of the rows to zero or more new Dicts. |
| get | Get a row by its index number. |
| getRange | Return a new grid which is a slice of the rows in this grid. |
| getSafe | Get a row by its index number or if index is out of bounds then return null. |
| has | Return if this grid contains the given column name. |
| isEmpty | Convenience for size equal to zero. |
| isErr | Return if this is an error grid - meta has "err" tag. |
| isHisGrid | Return if this grid conforms to the history grid shape |
| join | Join two grids by column name. |
| keepCols | Return a new grid with all the columns removed except the given columns. |
| last | Get the last row or return null if grid is empty. |
| map | Return a new grid which maps the rows to new Dict. |
| mapToList | Map each row to a list of values. |
| meta | Meta-data for entire grid |
| missing | Return if this grid does not contains the given column name. |
| removeCol | Return a new grid with the given column removed. |
| removeCols | Return a new grid with all the given columns removed. |
| renameCol | Return a new grid with the given column renamed. |
| renameCols | Return a new grid with multiple columns renamed. |
| reorderCols | Return a new grid with the columns reordered. |
| replace | Replace every cell with the given from value with the to value. |
| setColMeta | Return new grid with column meta-data replaced by given meta. |
| setMeta | Return a new grid with grid level meta-data replaced by given meta. |
| size | Get the number of rows in the grid. |
| sort | Return a new Grid which is a copy of this grid with the rows sorted by the given comparator function. |
| sortCol | Convenience for sort which sorts the given column. |
| sortColr | Sort the given column in reverse. |
| sortDis | Sort using Etc.compareDis and Dict.dis. |
| sortr | Return a new Grid which is a copy of this grid with the rows reverse sorted by the given comparator function. |
| unique | Return a new grid with only rows that define a unique key by the given key columns. |
Slot Details
addCol
Grid addCol(Str name, Obj? meta, |Row,Int->Obj?| f)
Return a new grid with an additional column. The cells of the column are created by calling the mapping function for each row. The meta may be any value accepted by Etc.makeDict
addColMeta
Grid addColMeta(Obj col, Obj? meta)
Return a new grid with additional column meta-data. The new tags are merged according to Etc.dictMerge. The col parameter may be either a Col or column name. The meta may be any value accepted by Etc.makeDict. If column is not found then return this. Also see setColMeta.
addCols
Grid addCols(Grid x)
Return a new grid by adding the given grid as a new set of columns to this grid. If the given grid contains duplicate column names, then they are given auto-generated unique names. If the given grid contains fewer rows then this grid, then the missing cells are filled with null.
addMeta
Grid addMeta(Obj? meta)
Return a new grid with additional grid level meta-data. The new tags are merged according to Etc.dictMerge. The meta may be any value accepted by Etc.makeDict Also see setMeta.
all
Bool all(|Row,Int->Bool| f)
Return true if the function returns true for all of the rows in the grid. If the grid is empty, return false.
any
Bool any(|Row,Int->Bool| f)
Return true if the function returns true for any of the rows in the grid. If the grid is empty, return false.
col
abstract Col? col(Str name, Bool checked := true)
Get a column by its name. If not resolved then return null or throw UnknownNameErr based on checked flag.
colDisNames
Str[] colDisNames()
Convenience for cols mapped to Col.dis. The resulting list is safe for mutating.
colNames
Str[] colNames()
Convenience for cols mapped to Col.name. The resulting list is safe for mutating.
colToList
Obj?[] colToList(Obj col, Type listOf := sys::Obj?#)
Get a column as a list of the cell values ordered by row.
cols
abstract Col[] cols()
Columns
colsToLocale
Grid colsToLocale()
Return a new Grid wich each col name mapped to its localized tag name if the col does not already have a display string. See Etc.tagToLocale and Localization.
commit
Grid commit(Grid diffs)
Return a new Grid which is the result of applying the given diffs to this grid. The diffs must have the same number of rows as this grid. Any cells in the diffs with a Remove.val are removed from this grid, otherwise they are updated/added.
each
abstract Void each(|Row,Int| f)
Iterate the rows
eachWhile
abstract Obj? eachWhile(|Row,Int->Obj?| f)
Iterate every row until the function returns non-null. If function returns non-null, then break the iteration and return the resulting object. Return null if the function returns null for every item
filter
Grid filter(Filter filter, HaystackContext? cx := null)
Return a new grid which finds matching rows based on the given filter. Also see findAll.
find
Row? find(|Row,Int->Bool| f)
Find one matching row or return null if no matches. Also see findIndex and findAll.
findAll
Grid findAll(|Row,Int->Bool| f)
Return a new grid which finds matching the rows in this grid. The has the same meta and column definitions. Also see find and filter.
findIndex
Int? findIndex(|Row,Int->Bool| f)
Find one matching row index or return null if no matches. Also see find.
first
abstract Row? first()
Get the first row or return null if grid is empty.
flatMap
Grid flatMap(|Row,Int->Obj?| f)
Return a new grid which maps each of the rows to zero or more new Dicts. The grid meta and existing column meta are maintained. New columns have empty meta.
get
@Operator abstract Row get(Int index)
Get a row by its index number. Throw UnsupportedErr is the grid doesn't support indexed based row access.
getRange
@Operator Grid getRange(Range r)
Return a new grid which is a slice of the rows in this grid. Negative indexes may be used to access from the end of the grid. The has the same meta and column definitions.
getSafe
abstract Row? getSafe(Int index)
Get a row by its index number or if index is out of bounds then return null. Throw UnsupportedErr is the grid doesn't support indexed based row access.
has
Bool has(Str name)
Return if this grid contains the given column name.
isEmpty
Bool isEmpty()
Convenience for size equal to zero.
isErr
Bool isErr()
Return if this is an error grid - meta has "err" tag.
isHisGrid
Bool isHisGrid()
Return if this grid conforms to the history grid shape:
- has at least two columns
- first column is named "ts"
- has meta hisStart and hisEnd DateTime values
This method does not check timezones or the ts cells.
join
Grid join(Grid that, Obj joinCol)
Join two grids by column name. The joinCol parameter may be a Col or col name. Current implementation requires:
- grids cannot have conflicting col names (other than join col)
- each row in both grids must have a unique value for join col
- grid level meta is merged
- join column meta is merged
keepCols
Grid keepCols(Obj[] toKeep)
Return a new grid with all the columns removed except the given columns. The toKeep columns can be Col instances or column names. Columns not found are silently ignored.
last
virtual Row? last()
Get the last row or return null if grid is empty. Throw UnsupportedErr is the grid doesn't support indexed based row access.
map
Grid map(|Row,Int->Obj?| f)
Return a new grid which maps the rows to new Dict. The grid meta and existing column meta are maintained. New columns have empty meta. If the mapping function returns null, then the row is removed.
mapToList
Obj?[] mapToList(|Row,Int->Obj?| f)
Map each row to a list of values.
meta
abstract Dict meta()
Meta-data for entire grid
missing
Bool missing(Str name)
Return if this grid does not contains the given column name.
removeCol
Grid removeCol(Obj col)
Return a new grid with the given column removed. The col parameter may be either a Col or column name. If column doesn't exist return this grid.
removeCols
Grid removeCols(Obj[] toRemove)
Return a new grid with all the given columns removed. The toRemove columns can be Col instances or column names. Columns not found are silently ignored.
renameCol
Grid renameCol(Obj oldCol, Str newName)
Return a new grid with the given column renamed. The oldCol parameter may be a Col or col name.
renameCols
Grid renameCols(Obj:Str oldToNew)
Return a new grid with multiple columns renamed. The given map is keyed old column names and maps to new column names. Any column names not found are ignored.
reorderCols
Grid reorderCols(Obj[] cols)
Return a new grid with the columns reordered. The given list of names represents the new order and must contain the same current Col instances or column names. Any column names not found are ignored.
replace
Grid replace(Obj? from, Obj? to)
Replace every cell with the given from value with the to value. The resulting grid has the same grid and col meta. Replacement comparison is by via Fantom equality via == operator, so it will only replace scalar values or null.
setColMeta
Grid setColMeta(Obj col, Obj? meta)
Return new grid with column meta-data replaced by given meta. The col parameter may be either a Col or column name. The meta may be any value accepted by Etc.makeDict If column is not found then return this. Also see addColMeta.
setMeta
Grid setMeta(Obj? meta)
Return a new grid with grid level meta-data replaced by given meta. The meta may be any value accepted by Etc.makeDict. Also see addMeta.
size
abstract Int size()
Get the number of rows in the grid. Throw UnsupportedErr if the grid doesn't support a size.
sort
Grid sort(|Row,Row->Int| f)
Return a new Grid which is a copy of this grid with the rows sorted by the given comparator function.
sortCol
Grid sortCol(Obj col)
Convenience for sort which sorts the given column. The col parameter can be a Col or a str name. The sorting algorithm used is the same one used by the table UI based on the localized display string. If column is not found then return this.
sortColr
Grid sortColr(Obj col)
Sort the given column in reverse. See sortCol
sortDis
Grid sortDis()
Sort using Etc.compareDis and Dict.dis.
sortr
Grid sortr(|Row,Row->Int| f)
Return a new Grid which is a copy of this grid with the rows reverse sorted by the given comparator function.
unique
Grid unique(Obj[] keyCols)
Return a new grid with only rows that define a unique key by the given key columns. If multiple rows have the same key cells, then the first row is returned and subsequent rows are removed. The keyCols can be Col instances or column names.
GridBuilder
@Js class GridBuilder : Obj
GridBuilder is used to build up an immutable Grid. To use first define your cols via addCol and then add the rows via addRow:
gb := GridBuilder()
gb.addCol("a").addCol("b")
gb.addRow(["a-0", "b-0"])
gb.addRow(["a-1", "b-1"])
grid := gb.toGridMethods
| addCol | Add column to the grid. |
| addColNames | Add list of column names to the grid. |
| addDictRow | Add dict as a new row to the grid. |
| addDictRows | Convience for adding a list of addDictRow. |
| addGridRows | Add all the rows of given grid as rows to our grid |
| addRow | Add list of cells as a new row to the grid. |
| numCols | Number of columns added to the grid |
| numRows | Number of rows added to the grid |
| setMeta | Set the grid meta (overwrites any current meta) The meta parameter can be any Etc.makeDict value. |
| toGrid | Construct to finalized grid |
Slot Details
addCol
This addCol(Str name, Obj? meta := null)
Add column to the grid. The meta parameter can be any Etc.makeDict value.
addColNames
This addColNames(Str[] names)
Add list of column names to the grid.
addDictRow
This addDictRow(Dict? row)
Add dict as a new row to the grid. All the dict tags must have been defined as columns.
addDictRows
This addDictRows(Dict?[] rows)
Convience for adding a list of addDictRow.
addGridRows
This addGridRows(Grid grid)
Add all the rows of given grid as rows to our grid
addRow
This addRow(Obj?[] cells)
Add list of cells as a new row to the grid. The cell list size must match the number of columns.
numCols
Int numCols()
Number of columns added to the grid
numRows
Int numRows()
Number of rows added to the grid
setMeta
This setMeta(Obj? meta)
Set the grid meta (overwrites any current meta) The meta parameter can be any Etc.makeDict value.
toGrid
Grid toGrid()
Construct to finalized grid
HaystackContext
@Js mixin HaystackContext : XetoContext
HaystackContext defines an environment of defs and data
Slot Details
HaystackTest
@Js abstract class HaystackTest : Test
HaystackTest provides convenience methods for testing common Haystack data structures.
Fields
| m | Convenience for Marker.val |
Methods
| n | Convenience for constructing a Number where unit may be either a Str name or a Unit instance. |
| verifyDictEq | Verify two Dictts have same name/val pairs |
| verifyGridEq | Verify that two grids are equal (meta, cols, and rows) |
| verifyGridIsEmpty | Verify that given grid is empty (has no rows) |
| verifyListEq | Verify contents of two lists using verifyValEq |
| verifyRefEq | Verify two Refs are equal for both id and dis |
| verifyValEq | Verify two Haystack values are equal. |
Slot Details
m
const static Marker m := Marker.val
Convenience for Marker.val
n
static Number? n(Num? val, Obj? unit := null)
Convenience for constructing a Number where unit may be either a Str name or a Unit instance.
verifyDictEq
Void verifyDictEq(Dict a, Obj b, Str? msg := null)
Verify two Dictts have same name/val pairs
verifyGridEq
Void verifyGridEq(Grid a, Grid b)
Verify that two grids are equal (meta, cols, and rows)
verifyGridIsEmpty
Void verifyGridIsEmpty(Grid g)
Verify that given grid is empty (has no rows)
verifyListEq
virtual Void verifyListEq(List a, List b, Str? msg := null)
Verify contents of two lists using verifyValEq
verifyRefEq
Void verifyRefEq(Ref a, Ref b, Str? msg := null)
Verify two Refs are equal for both id and dis
verifyValEq
Void verifyValEq(Obj? a, Obj? b, Str? msg := null)
Verify two Haystack values are equal. This method provides additional checking for types which don't support equal including:
- Ref.dis
- Dict
- Grid
HisItem
@Js const class HisItem : Obj, Dict
HisItem is a timestamp/value pair.
Constructors
| make | Construct timestamp/value pair. |
Fields
| ts | Timestamp of the history record. |
| val | Value at the timestamp. |
Methods
| compare | Ordering is based on timestamp. |
| each | |
| eachWhile | |
| equals | Equality is based on timestamp and value. |
| get | |
| has | |
| hash | Hash code is based on timestamp and value. |
| isEmpty | |
| map | |
| missing | |
| trap |
Slot Details
compare
virtual override Int compare(Obj that)
Ordering is based on timestamp.
each
virtual override Void each(|Obj,Str| f)
eachWhile
virtual override Obj? eachWhile(|Obj,Str->Obj?| f)
equals
virtual override Bool equals(Obj? that)
Equality is based on timestamp and value.
get
@Operator virtual override Obj? get(Str name, Obj? def := null)
has
virtual override Bool has(Str name)
hash
virtual override Int hash()
Hash code is based on timestamp and value.
isEmpty
virtual override Bool isEmpty()
make
new make(DateTime ts, Obj? val)
Construct timestamp/value pair.
map
virtual override This map(|Obj,Str->Obj| f)
missing
virtual override Bool missing(Str name)
trap
virtual override Obj? trap(Str name, Obj?[]? args := null)
ts
const DateTime ts
Timestamp of the history record.
val
const Obj? val
Value at the timestamp.
JsonReader
@Js class JsonReader : Obj
Read Haystack data in JSON format.
Constructors
| make | Wrap input stream. |
Fields
| opts |
Methods
| readGrid | Convenience for readVal as Grid |
| readVal | Read a value and auto close stream |
Slot Details
make
new make(InStream in, Dict? opts := null)
Wrap input stream. By default, the reader decodes JSON in the Haystack 4 (Hayson) format. Use the v3 option to decode JSON in the Haystack 3 format.
The following opts are supported:
v3(Marker): read JSON encoded in the Haystack 3 format
g := JsonReader(in).readGrid
val := JsonReader(in, Etc.makeDict(["v3":Marker.val])).readValopts
Dict opts { private set }
readGrid
virtual override Grid readGrid()
Convenience for readVal as Grid
readVal
Obj? readVal(Bool close := true)
Read a value and auto close stream
JsonWriter
@Js class JsonWriter : Obj
Write Haystack data in JSON format.
Constructors
| make | Wrap output stream. |
Fields
| opts |
Methods
| close | Close the underlying output stream |
| flush | Flush the underlying output stream and return this |
| valToStr | Get a value as a JSON string. |
| writeGrid | Write the grid and return this |
| writeVal | Write any haystack value |
Slot Details
close
Bool close()
Close the underlying output stream
flush
This flush()
Flush the underlying output stream and return this
make
new make(OutStream out, Dict? opts := null)
Wrap output stream. By default, the writer encodes JSON in the Haystack 4 (Hayson) format. Use the v3 option to encode JSON in the Haystack 3 format.
The following opts are supported:
v3(Marker): write JSON in the Haystack 3 format
JsonWriter(out).writeVal(Etc.makeDict(["ts": DateTime.now])).close
JsonWriter(out, Etc.makeDict(["v3":Marker.val])).writeGrid(grid).closeopts
Dict opts { private set }
valToStr
static Str valToStr(Obj? val)
Get a value as a JSON string.
writeGrid
virtual override This writeGrid(Grid grid)
Write the grid and return this
writeVal
This writeVal(Obj? val)
Write any haystack value
Kind
@Js abstract const class Kind : Obj
Kind provides a type signature for a Haystack data value
Constructors
| fromStr | Parse a signature to its Kind representation. |
Fields
| name | Name of kind: Bool, Number, List, etc |
| type | Fantom type for the kind |
Methods
| equals | Equality is based signature |
| fromDefName | Lookup Kind from its lower case def name |
| fromType | Lookup Kind for a Fantom type |
| fromVal | Lookup Kind for a Fantom object |
| hash | Hash is based signature |
| toStr | Return signature |
Slot Details
equals
virtual override Bool equals(Obj? that)
Equality is based signature
fromDefName
static Kind? fromDefName(Str name, Bool checked := true)
Lookup Kind from its lower case def name
fromStr
static new fromStr(Str signature, Bool checked := true)
Parse a signature to its Kind representation. If it cannot be parsed to a known kind, then return null or raise an exception.
fromType
static Kind? fromType(Type? type, Bool checked := true)
Lookup Kind for a Fantom type
fromVal
static Kind? fromVal(Obj? val, Bool checked := true)
Lookup Kind for a Fantom object
hash
virtual override Int hash()
Hash is based signature
name
const Str name
Name of kind: Bool, Number, List, etc
toStr
virtual override Str toStr()
Return signature
type
const Type type
Fantom type for the kind
Marker
@Js @Serializable { simple=true } const class Marker : Obj
Marker is the singleton which indicates a marker tag with no value.
Constructors
| fromStr | Always return val |
Fields
| val | Singleton value |
Methods
| fromBool | If true return Marker.val else null |
| toStr | Return "marker" |
Slot Details
fromBool
static Marker? fromBool(Bool b)
If true return Marker.val else null
fromStr
static new fromStr(Str s)
Always return val
toStr
virtual override Str toStr()
Return "marker"
val
const static Marker val := ...
Singleton value
NA
@Js @Serializable { simple=true } const class NA : Obj
NA is the singleton which indicates not available.
Constructors
| fromStr | Always return val |
Fields
| val | Singleton value |
Methods
| toStr | Return "NA" |
Slot Details
fromStr
static new fromStr(Str s)
Always return val
toStr
virtual override Str toStr()
Return "NA"
val
const static NA val := ...
Singleton value
Namespace
@Js const mixin Namespace
Namespace models a symbolic namespace of defs
Methods
| def | Resolve def by its symbol string key |
Slot Details
def
abstract Def? def(Str symbol, Bool checked := true)
Resolve def by its symbol string key
Number
@Js @Serializable { simple=true } const class Number : Obj
Number represents a numeric value and an optional Unit.
Constructors
| fromStr | Parse from a string according to zinc syntax |
| make | Construct from scalar value and optional unit. |
| makeDuration | Construct from a duration, standardize unit is hours If unit is null, then a best attempt is made based on magnitude. |
| makeInt | Construct from scalar integer and optional unit. |
Fields
| defVal | Default value is zero with no unit |
| nan | Constant for not-a-number |
| negInf | Constant for negative infinity |
| negOne | Constant for -1 with no unit |
| one | Constant for 1 with no unit |
| posInf | Constant for positive infinity |
| ten | Constant for 10 with no unit |
| zero | Constant for 0 with no unit |
Methods
| abs | Return absolute value of this number. |
| approx | Return if this number is approximately equal to that - see Float.approx |
| clamp | Clamp this number between the min and max. |
| compare | Compare is based on val. |
| decrement | Decrement this number. |
| div | Divide this by b. |
| equals | Equality is based on val and unit. |
| hash | Hash is based on val |
| increment | Increment this number. |
| isDuration | Does this number have a time unit which can be converted to a Fantom Duration instance. |
| isInt | Is this number a whole integer without a fractional part |
| isNaN | Is the floating value NaN. |
| isNegative | Is this a negative number |
| isSpecial | Return if this number if pos/neg infinity or NaN |
| lower | Get the ASCII lower case version of this number as a Unicode point. |
| makeNum | Construct from scalar Int, Float, or Decimal and optional unit. |
| max | Return max value. |
| min | Return min value. |
| minus | Subtract b from this. |
| mod | Return remainder of this divided by b. |
| mult | Multiple this and b. |
| negate | Negate this number. |
| plus | Add this with b. |
| toCode | Trio/zinc code representation, same as toStr |
| toDuration | Get this number as a Fantom Duration instance |
| toFloat | Get the scalar value as an Float |
| toInt | Get the scalar value as an Int |
| toLocale | Format the number using given pattern which is an superset of Float.toLocale |
| toStr | String representation |
| unit | Get unit associated with this number or null. |
| upper | Get the ASCII upper case version of this number as a Unicode point. |
Slot Details
abs
Number abs()
Return absolute value of this number.
approx
Bool approx(Number that, Float? tolerance := null)
Return if this number is approximately equal to that - see Float.approx
clamp
Number clamp(Number min, Number max)
Clamp this number between the min and max. If its less than min then return min, if its greater than max return max, otherwise return this number itself. The min and max must have matching units or be unitless. The result is always in the same unit as this instance.
compare
virtual override Int compare(Obj that)
Compare is based on val. Throw UnitErr is this and b have incompatible units.
decrement
@Operator Number decrement()
Decrement this number. Shortcut is --a.
defVal
const static Number defVal := Number.<ctor>(0.0)
Default value is zero with no unit
div
@Operator Number div(Number b)
Divide this by b. Shortcut is a/b. The resulting unit is derived from the quotient of this and b. Throw UnitErr if a/b does not match a unit in the unit database.
equals
virtual override Bool equals(Obj? that)
Equality is based on val and unit. NaN is equal to itself (like Float.compare, but unlike Float.equals)
fromStr
static new fromStr(Str s, Bool checked := true)
Parse from a string according to zinc syntax
hash
virtual override Int hash()
Hash is based on val
increment
@Operator Number increment()
Increment this number. Shortcut is ++a.
isDuration
Bool isDuration()
Does this number have a time unit which can be converted to a Fantom Duration instance.
isInt
Bool isInt()
Is this number a whole integer without a fractional part
isNaN
Bool isNaN()
Is the floating value NaN.
isNegative
Bool isNegative()
Is this a negative number
isSpecial
Bool isSpecial()
Return if this number if pos/neg infinity or NaN
lower
Number lower()
Get the ASCII lower case version of this number as a Unicode point.
make
new make(Float val, Unit? unit := null)
Construct from scalar value and optional unit.
makeDuration
new makeDuration(Duration dur, Unit? unit := @hr)
Construct from a duration, standardize unit is hours If unit is null, then a best attempt is made based on magnitude.
makeInt
static new makeInt(Int val, Unit? unit := null)
Construct from scalar integer and optional unit.
makeNum
static Number makeNum(Num val, Unit? unit := null)
Construct from scalar Int, Float, or Decimal and optional unit.
max
Number max(Number that)
Return max value. Units are not checked for this comparison.
min
Number min(Number that)
Return min value. Units are not checked for this comparison.
minus
@Operator Number minus(Number b)
Subtract b from this. Shortcut is a-b. The b.unit must match this.unit.
mod
@Operator Number mod(Number b)
Return remainder of this divided by b. Shortcut is a%b. The unit of b must be null.
mult
@Operator Number mult(Number b)
Multiple this and b. Shortcut is a*b. The resulting unit is derived from the product of this and b. Throw UnitErr if a*b does not match a unit in the unit database.
nan
const static Number nan := Number.<ctor>(Float.nan)
Constant for not-a-number
negInf
const static Number negInf := Number.<ctor>(Float.negInf)
Constant for negative infinity
negOne
const static Number negOne := Number.<ctor>(-1.0)
Constant for -1 with no unit
negate
@Operator Number negate()
Negate this number. Shortcut is -a.
one
const static Number one := Number.<ctor>(1.0)
Constant for 1 with no unit
plus
@Operator Number plus(Number b)
Add this with b. Shortcut is a+b. Throw UnitErr is this and b have incompatible units.
posInf
const static Number posInf := Number.<ctor>(Float.posInf)
Constant for positive infinity
ten
const static Number ten := Number.<ctor>(10.0)
Constant for 10 with no unit
toCode
Str toCode()
Trio/zinc code representation, same as toStr
toDuration
Duration? toDuration(Bool checked := true)
Get this number as a Fantom Duration instance
toFloat
Float toFloat()
Get the scalar value as an Float
toInt
Int toInt()
Get the scalar value as an Int
toLocale
Str toLocale(Str? pattern := null)
Format the number using given pattern which is an superset of Float.toLocale:
# optional digit
0 required digit
. decimal point
, grouping separator (only last one before decimal matters)
U position of unit (default to suffix)
pos;neg separate negative format (must specify U position)When using the pos;neg pattern, the "U" position must be specified in both pos and neg patterns, otherwise the unit is omitted. Note that the negative pattern always uses mimics the positive pattern for the actual digit formatting (#, 0, decimal, and grouping).
The special "B" pattern is used to format bytes; see Int.toLocale.
If pattern is null, the following rules are used:
- If
isDurationtrue, then return best fit unit is selected - If unit is non-null attempt to lookup a unit specific default pattern with the locale key "haystack::number.{unit.name}".
- If
isInttrue, then returnInt.toLocaleusing sys locale default - Return
Float.toLocaleusing sys locale default
Examples:
Number Pattern Result Notes
------ ------- ------- ------
12.34 "#.####" 12.34 Optional fractional digits
12.34 "#.0000" 12.3400 Required fractional digits
12.34$ null $12.34 Haystack locale default
12$ "U 0.00" $ 12.00 Explicit unit placement
-12$ "U0.##;(U#)" ($12) Alternative negative format
45% "+0.0U;-0.0U" +45% Use leading positive signtoStr
virtual override Str toStr()
String representation
unit
Unit? unit()
Get unit associated with this number or null.
upper
Number upper()
Get the ASCII upper case version of this number as a Unicode point.
zero
const static Number zero := Number.<ctor>(0.0)
Constant for 0 with no unit
Ref
@Js @Serializable { simple=true } const class Ref : Ref
Ref is used to model a record identifier and optional display string.
Constructors
| fromStr | Make with simple id |
| make | Construct with id string and optional display string. |
| makeWithDis | Construct with Ref id string and optional display string. |
Fields
| defVal | Default is nullRef |
| nullRef | Null ref is "@null" |
Methods
| dis | Return display value of target if available, otherwise id |
| equals | Equality is based on id only (not dis). |
| gen | Generate a unique Ref. |
| hash | Hash id |
| id | Identifier which does not include the leading @ |
| isId | Return if the string is a valid Ref identifier. |
| isIdChar | Is the given character a valid id char |
| isNull | Null ref has id value of "null"? |
| isSpec | Is this a spec ref with double colons |
| toCode | Return "@id" |
| toId | Take an arbitrary string and convert into a safe Ref identifier. |
| toStr | String format is id which does not include the leading @. |
Slot Details
defVal
const static Ref defVal := nullRef
Default is nullRef
dis
virtual override Str dis()
Return display value of target if available, otherwise id
equals
virtual override Bool equals(Obj? that)
Equality is based on id only (not dis).
fromStr
static new fromStr(Str id, Bool checked := true)
Make with simple id
gen
static Ref gen()
Generate a unique Ref.
hash
virtual override Int hash()
Hash id
id
virtual override Str id()
Identifier which does not include the leading @
isId
static Bool isId(Str n)
Return if the string is a valid Ref identifier. See isIdChar
isIdChar
static Bool isIdChar(Int char)
Is the given character a valid id char:
A-Za-z0-9_ : - . ~
isNull
Bool isNull()
Null ref has id value of "null"?
isSpec
Bool isSpec()
Is this a spec ref with double colons
make
static new make(Str id, Str? dis)
Construct with id string and optional display string.
makeWithDis
static new makeWithDis(Ref ref, Str? dis := null)
Construct with Ref id string and optional display string.
nullRef
const static Ref nullRef := Ref.<ctor>("null")
Null ref is "@null"
toCode
Str toCode()
Return "@id"
toId
static Str toId(Str n)
Take an arbitrary string and convert into a safe Ref identifier.
toStr
virtual override Str toStr()
String format is id which does not include the leading @. Use toCode to include leading @.
Remove
@Js const class Remove : Obj
Remove is the singleton which indicates a remove operation.
Fields
| val | Singleton value |
Methods
| toStr | Return "remove" |
Slot Details
toStr
virtual override Str toStr()
Return "remove"
val
const static Remove val := ...
Singleton value
Row
@Js abstract const class Row : Obj, Dict
Row of a Grid. Row also implements the Dict mixin to expose all of the columns as name/value pairs.
Methods
| dis | Get display string for dict or the given tag. |
| each | Iterate through all the columns. |
| eachWhile | Iterate through all the columns until function returns null, then break iteration and return the result. |
| get | Get the column val by name. |
| grid | Parent grid |
| has | Return true if the given name is mapped to a non-null column val. |
| isEmpty | Always returns false. |
| missing | Return true if the given name is not mapped to a non-null column val. |
| trap | Get the column val by name. |
| val | Scalar value for the cell |
Slot Details
dis
virtual override Str? dis(Str? name := null, Str? def := "")
Get display string for dict or the given tag. The Row implementation follows all the same rules as Dict.dis with following enhancements:
If the column meta defines a "format" pattern, then it is used to format the value via the appropiate toLocale method.
each
virtual override Void each(|Obj,Str| f)
Iterate through all the columns.
eachWhile
virtual override Obj? eachWhile(|Obj,Str->Obj?| f)
Iterate through all the columns until function returns null, then break iteration and return the result.
get
@Operator virtual override Obj? get(Str name, Obj? def := null)
Get the column val by name. If column name doesn't exist or if the column value is null, then return def.
grid
abstract Grid grid()
Parent grid
has
virtual override Bool has(Str name)
Return true if the given name is mapped to a non-null column val.
isEmpty
virtual override Bool isEmpty()
Always returns false.
missing
virtual override Bool missing(Str name)
Return true if the given name is not mapped to a non-null column val.
trap
virtual override Obj? trap(Str name, Obj?[]? args := null)
Get the column val by name. If column name doesn't exist or if the column value is null, then throw UnknownNameErr.
val
abstract Obj? val(Col col)
Scalar value for the cell
Span
@Js const class Span : Obj
Span models a range of time using an inclusive starting timestamp and exclusive ending timestamp.
Constructors
| fromStr | Decode from string format |
| makeAbs | Make an absolute span for two date times which must be defined in the Rel timezone |
| makeDate | Make an absolute span for the given date |
| makeRel | Make a relative span for given mode using current time and current locale for starting weekday |
Fields
| end | Exclusive ending timestamp |
| mode | Absolute or relative mode |
| start | Inclusive starting timestamp |
Methods
| dis | Display string for current locale |
| equals | Equality is based on mode only for relative, start/end for abs |
| hash | Hash code is based on mode only for relative, start/end for abs |
| toCode | Return axon representation for this span. |
| toDateSpan | Convert this span to a DateSpan attempting to use aligned dates |
| toStr | Encode to string, see fromStr |
| toTimeZone | Convert to timezone using DateTime.toTimeZone on both start, end |
| today | Convenience for Span(SpanMode.today) |
| tz | Timezone for this span |
Slot Details
dis
Str dis()
Display string for current locale
end
const DateTime end
Exclusive ending timestamp
equals
virtual override Bool equals(Obj? obj)
Equality is based on mode only for relative, start/end for abs
fromStr
static new fromStr(Str str, TimeZone tz := TimeZone.cur(), Bool checked := true)
Decode from string format:
- relative
SpanModemode name - absolute single date:
YYYY-MM-DD - absolute date span:
YYYY-MM-DD,YYYY-MM-DD - absolute date time span:
YYYY-MM-DDThh:mm:ss.FFF zzzz,YYYY-MM-DDThh:mm:ss.FFF zzzz
hash
virtual override Int hash()
Hash code is based on mode only for relative, start/end for abs
makeAbs
static new makeAbs(DateTime start, DateTime end)
Make an absolute span for two date times which must be defined in the Rel timezone
makeDate
static new makeDate(Date date, TimeZone tz := TimeZone.cur())
Make an absolute span for the given date
makeRel
static new makeRel(SpanMode mode, TimeZone tz := TimeZone.cur())
Make a relative span for given mode using current time and current locale for starting weekday
mode
const SpanMode mode
Absolute or relative mode
start
const DateTime start
Inclusive starting timestamp
toCode
Str toCode()
Return axon representation for this span.
toDateSpan
DateSpan toDateSpan()
Convert this span to a DateSpan attempting to use aligned dates
toStr
virtual override Str toStr()
Encode to string, see fromStr
toTimeZone
Span toTimeZone(TimeZone tz)
Convert to timezone using DateTime.toTimeZone on both start, end
today
static Span today(TimeZone tz := TimeZone.cur())
Convenience for Span(SpanMode.today)
tz
TimeZone tz()
Timezone for this span
SpanMode
@Js @Serializable { simple=true } enum class SpanMode : Enum
SpanMode enumerates relative or absolute span modes
Enum
| abs | |
| today | |
| yesterday | |
| thisWeek | |
| lastWeek | |
| pastWeek | |
| thisMonth | |
| lastMonth | |
| pastMonth | |
| thisQuarter | |
| lastQuarter | |
| pastQuarter | |
| thisYear | |
| lastYear | |
| pastYear |
Constructors
| fromStr | Return the SpanMode instance for the specified name. |
Fields
| vals | List of SpanMode values indexed by ordinal |
Methods
| dis | Display name for relative period |
| isAbs | Is this an absolute mode |
| isRel | Is this a relative mode |
Slot Details
abs
const static SpanMode abs := ...
dis
Str dis()
Display name for relative period
fromStr
static new fromStr(Str name, Bool checked := true)
Return the SpanMode instance for the specified name. If not a valid name and checked is false return null, otherwise throw ParseErr.
isAbs
Bool isAbs()
Is this an absolute mode
isRel
Bool isRel()
Is this a relative mode
lastMonth
const static SpanMode lastMonth := ...
lastQuarter
const static SpanMode lastQuarter := ...
lastWeek
const static SpanMode lastWeek := ...
lastYear
const static SpanMode lastYear := ...
pastMonth
const static SpanMode pastMonth := ...
pastQuarter
const static SpanMode pastQuarter := ...
pastWeek
const static SpanMode pastWeek := ...
pastYear
const static SpanMode pastYear := ...
thisMonth
const static SpanMode thisMonth := ...
thisQuarter
const static SpanMode thisQuarter := ...
thisWeek
const static SpanMode thisWeek := ...
thisYear
const static SpanMode thisYear := ...
today
const static SpanMode today := ...
vals
const static SpanMode[] vals := ...
List of SpanMode values indexed by ordinal
yesterday
const static SpanMode yesterday := ...
Symbol
@Js abstract const class Symbol : Obj
Symbol is a name to a def in the meta-model namespace
Constructors
| fromStr | Construct from string |
Methods
| equals | Equality is based on string representation |
| hash | Hash code is based on string representation |
| name | Simple name |
| toCode | Code representation with leading "^" caret. |
| toStr | String representation |
Slot Details
equals
virtual override Bool equals(Obj? that)
Equality is based on string representation
fromStr
static new fromStr(Str s, Bool checked := true)
Construct from string
hash
virtual override Int hash()
Hash code is based on string representation
name
abstract Str name()
Simple name
toCode
Str toCode()
Code representation with leading "^" caret.
toStr
virtual override Str toStr()
String representation
TrioReader
@Js class TrioReader : Obj
Read Haystack data in Trio format.
Constructors
| make | Wrap input stream |
Methods
| eachDict | Iterate through the entire stream reading dicts. |
| readAllDicts | Read all dicts from the stream and close it. |
| readDict | Read next dict from the stream. |
| readGrid | Return recs as simple grid (no grid or column level meta) |
Slot Details
eachDict
Void eachDict(|Dict| f)
Iterate through the entire stream reading dicts. The stream is guaranteed to be closed when done.
make
new make(InStream in)
Wrap input stream
readAllDicts
Dict[] readAllDicts()
Read all dicts from the stream and close it.
readDict
Dict? readDict(Bool checked := true)
Read next dict from the stream. If end of stream is detected then reutrn null or raise exception based on checked flag.
readGrid
virtual override Grid readGrid()
Return recs as simple grid (no grid or column level meta)
TrioWriter
@Js class TrioWriter : Obj
Write Haystack data in Trio format.
Options:
- noSort: do not sort tag names
Constructors
| make | Wrap output stream |
Methods
| close | Close the underlying output stream |
| writeAllDicts | Write the list of dicts. |
| writeDict | Write separator and record. |
| writeGrid | Write the grid rows (no support for meta) |
Slot Details
close
Bool close()
Close the underlying output stream
make
new make(OutStream out, Dict? opts := null)
Wrap output stream
writeAllDicts
This writeAllDicts(Dict[] dicts)
Write the list of dicts. Return this.
writeDict
This writeDict(Dict dict)
Write separator and record. Return this.
writeGrid
virtual override This writeGrid(Grid grid)
Write the grid rows (no support for meta)
TypedDict
@Js const class TypedDict : Obj, Dict
TypedDict wraps a dict that maps tags to statically typed fields. To use this API:
- Create subclass of TypedDict
- Annotate const instance fields with
@TypedTag - Create constructor with Dict and it-block callback
- Optionally create convenience factory that calls
create
The following coercions are supported:
- Int field from Number tag
- Duration field from Number tag
- Bool field from Marker tag
Example:
const class ExampleRec : TypedDict
{
static new wrap(Dict d, |Str|? onErr := null) { create(ExampleRec#, d, onErr) }
new make(Dict d, |This| f) : super(d) { f(this) }
@TypedTag const Int limit := 99
@TypedTag const Duration timeout := 3sec
}Constructors
| make | Sub constructor. |
Methods
| create | Factory to create for given type and dict to wrap. |
| each | Iterate the wrapped dict tags |
| eachWhile | Iterate the wrapped dict tags until callback returns non-null |
| get | Get a tag from wrapped dict |
| has | Return if wrapped dict has given tag |
| isEmpty | Return if wrapped dict is empty |
| meta | Wrapped dict for this instance |
| missing | Return if wrapped dict is missing given tag |
| trap | Trap on the wrapped dict |
Slot Details
create
static TypedDict create(Type type, Dict meta, |Str|? onErr := null)
Factory to create for given type and dict to wrap. Invalid tag values are logged to the given callback if provided.
each
virtual override Void each(|Obj,Str| f)
Iterate the wrapped dict tags
eachWhile
virtual override Obj? eachWhile(|Obj,Str->Obj?| f)
Iterate the wrapped dict tags until callback returns non-null
get
@Operator virtual override Obj? get(Str n, Obj? def := null)
Get a tag from wrapped dict
has
virtual override Bool has(Str n)
Return if wrapped dict has given tag
isEmpty
virtual override Bool isEmpty()
Return if wrapped dict is empty
make
new make(Dict meta)
Sub constructor.
meta
Dict meta()
Wrapped dict for this instance
missing
virtual override Bool missing(Str n)
Return if wrapped dict is missing given tag
trap
virtual override Obj? trap(Str n, Obj?[]? a := null)
Trap on the wrapped dict
TypedTag
@Js @Serializable facet class TypedTag : Obj, Facet
Facet to annotate a TypedDict field.
Fields
| meta | Meta data for the def encoded as a Trio string |
Slot Details
meta
const Str meta := ""
Meta data for the def encoded as a Trio string
UnitErr
@Js const class UnitErr : Err
UnitErr indicates an operation between two incompatible units
Constructors
| make | Construct with message and optional cause. |
Slot Details
make
new make(Str? msg, Err? cause := null)
Construct with message and optional cause.
UnknownNameErr
@Js const class UnknownNameErr : Err
UnknownNameErr is thrown when Dict.trap or Grid.col fails to resolve a name.
Constructors
| make | Construct with message and optional cause. |
Slot Details
make
new make(Str? msg, Err? cause := null)
Construct with message and optional cause.
UnknownRecErr
@Js const class UnknownRecErr : Err
UnknownKindErr when a Kind cannot be resolved or parsed
Constructors
| make | Construct with message and optional cause. |
Slot Details
make
new make(Str? msg, Err? cause := null)
Construct with message and optional cause.
ValidateErr
@Js const class ValidateErr : Err
ValidateErr when a validation fails. The msg should be localized for display to users.
Constructors
| make |
Slot Details
make
new make(Str msg, Err? cause := null)
XStr
@Js const class XStr : Obj
XStr is an extended string which is a type name and value encoded as a string. It is used as a generic value when an XStr is decoded without any predefind Fantom type.
Constructors
| make | Construct for type name and string value |
Fields
| type | Type name |
| val | String value |
Methods
| decode | Decode into its appropiate Fantom type or fallback to generic XStr |
| equals | Equality is base on type and val |
| hash | Hash is composed of type and val |
| toStr |
Slot Details
decode
static Obj decode(Str type, Str val)
Decode into its appropiate Fantom type or fallback to generic XStr
equals
virtual override Bool equals(Obj? obj)
Equality is base on type and val
hash
virtual override Int hash()
Hash is composed of type and val
make
new make(Str type, Str val)
Construct for type name and string value
toStr
virtual override Str toStr()
type
const Str type
Type name
val
const Str val
String value
ZincReader
@Js class ZincReader : Obj
Read Haystack data in Zinc format.
Constructors
| make | Wrap input stream |
Methods
| close | Close the underlying stream. |
| readGrid | Convenience for readVal as Grid |
| readVal | Read a value and auto close stream |
Slot Details
close
Bool close()
Close the underlying stream.
make
new make(InStream in)
Wrap input stream
readGrid
virtual override Grid readGrid()
Convenience for readVal as Grid
readVal
Obj? readVal(Bool close := true)
Read a value and auto close stream
ZincWriter
@Js class ZincWriter : Obj
Write Haystack data in Zinc format.
Constructors
| make | Wrap given output strea |
Methods
| close | Close underlying stream |
| flush | Flush underlying stream |
| gridToStr | Format a grid to a zinc string in memory. |
| valToStr | Get a value as a zinc string. |
| writeGrid | Write a grid to stream |
| writeVal | Write a zinc value |
Slot Details
close
This close()
Close underlying stream
flush
This flush()
Flush underlying stream
gridToStr
static Str gridToStr(Grid grid)
Format a grid to a zinc string in memory.
make
new make(OutStream out)
Wrap given output strea
valToStr
static Str valToStr(Obj? val)
Get a value as a zinc string.
writeGrid
virtual override This writeGrid(Grid grid)
Write a grid to stream
writeVal
Void writeVal(Obj? val)
Write a zinc value