Skip to content

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 ​

SpanModeSpanMode enumerates relative or absolute span modes

facets ​

TypedTagFacet to annotate a TypedDict field.

errs ​

CallErrCallErr is raised when a server returns an error grid from a client call to a REST operation.
DependErrDependErr indicates a missing dependency
DisabledErrDisabledErr indicates access of a disabled resource.
DownErrDownErr indicates a communications or networking problem
FaultErrFaultErr indicates a software or configuration problem
UnitErrUnitErr indicates an operation between two incompatible units
UnknownNameErrUnknownNameErr is thrown when Dict.trap or Grid.col fails to resolve a name.
UnknownRecErrUnknownKindErr when a Kind cannot be resolved or parsed
ValidateErrValidateErr 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

makeConstruct with mime type string.

Fields

defValBin for "text/plain; charset=utf-8".
mimeMimeType 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

metaGrid.meta from the error grid response
remoteTraceRemote 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

uriURI of endpoint such as "http://host/api/myProj/".

Methods

aboutCall "about" operation to query server summary info.
callCall the given REST operation with its request grid and return the response grid.
closeClose the session by sending the close op.
commitCommit a set of diffs.
evalEvaluate an Axon expression and return results as Grid.
openOpen with URI of project such as "http://host/api/myProj/".
readCall "read" operation to read a record that matches the given filter.
readAllCall "read" operation to read a record all recs which match the given filter.
readByIdCall "read" operation to read a record by its identifier.
readByIdsCall "read" operation to read a list of records by their identifiers.
toStrReturn 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

compareCompare based on name
disDisplay name for columm which is meta.dis(null, name)
equalsEquality is based on reference
metaMeta-data for column
nameProgramatic name identifier for columm
toStrString 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

fromStrDecode from string formatted as "C(lat,lng)"
makeConstruct from floating point decimal degrees

Fields

defValDefault value is "C(0.0,0.0)"

Methods

distCompute great-circle distance two coordinates using haversine forumula.
equalsEquality is based on lat/lng
hashHash is based on lat/lng
latLatitude in decimal degrees
lngLongtitude in decimal degrees
toStrRepresented 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

makeWrap input stream

Methods

readGridReturn 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

makeWrap output stream

Fields

delimiterDelimiter character; defaults to comma.
newlineNewline string; defaults to "\n"
showHeaderInclude the column names as a header row
stripUnitsStrip units from all numbers

Methods

closeClose the underlying output stream
flushFlush the underlying output stream and return this
writeGridWrite 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

fromStrConstruct DateSpan from Str.
makeConstruct a new DateSpan using a start date and period, or an explicit start date and end date.

Fields

dayConstant for a day period.
endInclusive end date for this span.
monthConstant for a month period.
numDaysGet number of days in this span.
periodThe period: day, week, month, quarter, year, or range.
quarterConstant for a quarter period.
rangeConstant for an arbitrary period.
startStart date for this span.
weekConstant for a week period.
yearConstant for a month period.

Methods

containsDoes this span inclusively contain the given Date inclusively
disReturn display name for this span.
eachDayIterate each day in this DateSpan.
eachMonthIterate each month in this date range as a range of first to last day in each month.
equalsObjects are equal if start, end, and period match.
hashHash is based on start/end/period.
isDayConvenience for period == DateSpan.day
isMonthConvenience for period == DateSpan.month
isQuarterConvenience for period == DateSpan.quarter
isRangeConvenience for period == DateSpan.range
isWeekConvenience for period == DateSpan.week
isYearConvenience for period == DateSpan.year
lastMonthConstruct for month previous to this month 1..28-31
lastQuarterDateSpan for 3 month quarter previous to this quarter
lastWeekConstruct for week previous to this week sun..sat (uses locale start of week)
lastYearConstruct for year previous to this year Jan-1..Dec-31
makeMonthConvenience for make(Date(year, month, 1), DateSpan.month).
makeWeekConvenience for make(start, DateSpan.week).
makeYearConvenience for make(Date(year, Month.jan, 1), DateSpan.year).
minusShift start and end by the given number of days.
nextReturn the next DateSpan based on the period
pastMonthConstruct for last 30days today-30days..today
pastWeekConstruct for last 7 days as today-7days..today
pastYearConstruct for this past today-365days..today
plusShift start and end by the given number of days.
prevReturn the previous DateSpan based on the period
thisMonthConstruct for this month as 1..28-31
thisQuarterDateSpan for this 3 month quarter
thisWeekConstruct for this week as sun..sat (uses locale start of week)
thisYearConstruct for this year Jan-1..Dec-31
toCodeReturn axon representation for this span.
toSpanConvert this instance to a Span instance
toStrStr representation is "<start>,<end
todayConvenience for make(Date.today).
yesterdayConvenience 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

nameReturn simple name of definition
symbolSymbolic 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

makeConstruct 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.isTagName rules
  • 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

_idTemp shim until we break backward compatibility
disGet display string for dict or the given tag.
eachIterate through the name/value pairs
eachWhileIterate through the name/value pairs until the given function returns non-null, then break the iteration and return resulting object.
getGet the value for the given name or def if name not mapped
hasReturn true if the given name is mapped to a non-null value.
idGet the id tag as a Ref or raise CastErr/UnknownNameErr
isEmptyReturn if the there are no name/value pairs
mapCreate a new instance of this dict with the same names, but apply the specified closure to generate new values.
missingReturn true if the given name is not mapped to a non-null value.
toStrReturn string for debugging only
trapGet 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

makeConstruct 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
compareDisGiven two display strings, return 1, 0, or -1 if a is less than, equal to, or greater than b.
dict0Empty dict singleton
dict1Create a Dict with one non-nullable name/value pair
dict2Create a Dict with two non-nullable name/value pairs
dict3Create a Dict with three non-nullable name/value pairs
dict4Create a Dict with four non-nullable name/value pairs
dict5Create a Dict with five non-nullable name/value pairs
dict6Create a Dict with six non-nullable name/value pairs
dictAllReturn if all of the tag name/value pairs match the given function.
dictAnyReturn if any of the tag name/value pairs match the given function.
dictEqReturn if two dicts are equal with same name/value pairs.
dictFindAllReturn a new Dict containing the name/value pairs for which f returns true.
dictHashKeyConstruct an object which wraps a dict and is suitable to use for a hash key in a Map.
dictMapApply the given map function to each name/value pair to construct a new Dict.
dictMergeAdd/set all the name/value pairs in a with those defined in b.
dictNamesGet a read/write list of the dict's name keys.
dictRemoveRemove a name/val pair from an exisiting dict, or if the name isn't found then return original dict.
dictRemoveAllRemove all names from the given dict.
dictRenameRename given name if its defined in the dict, otherwise return original.
dictSetSet a name/val pair in an existing dict or if dict is null then create a new dict with given name/val pair.
dictToDisGiven a dict, attempt to find the best display string
dictToHaystackCoerce dict to Haystack types, see toHaystack.
dictToMapConvert a Dict to a read/write map.
dictValsGet all the non-null values mapped by a dictionary.
dictsNamesGiven a list of dictionaries, find all the common names used.
discretePeriodsIterate a discrete period string formatted in base64.
emptyDictGet the emtpy Dict instance.
escapeTagNameEscape tag name into "__{utf-8 hex}" format
gridFlattenFlatten a list of grids into a single grid.
isEscapedTagNameReturn if tag name starts with "__" as escaped name
isKindNameReturn if the given string is a legal kind name
isTagNameReturn if the given string is a legal tag name
macroProcess macro pattern with given scope of variable name/value pairs.
macroVarsReturn the list of variable tag names used in the given macro pattern.
makeDictMake a Dict instance where val is one of the following
makeDict1Make a Dict with one name/value pair.
makeDict2Make a Dict with two name/value pairs.
makeDict3Make a Dict with three name/value pairs.
makeDict4Make a Dict with four name/value pairs.
makeDict5Make a Dict with five name/value pairs.
makeDict6Make a Dict with six name/value pairs.
makeDictGridConstruct a grid for a Dict row.
makeDictsMake a list of Dict instances using makeDict.
makeDictsGridConstruct a grid for a list of Dict rows.
makeEmptyGridConstruct an empty grid with just the given grid level meta-data.
makeErrGridConstruct a grid for an error response.
makeListGridConstruct a grid with one column for a list.
makeListsGridConstruct a grid for a list of rows, where each row is a list of cells.
makeMapGridConvenience for makeDictGrid
makeMapsGridConvenience for makeDictsGrid
relDisGet a relative display name.
tagToLocaleGet the localized string for the given tag name for the current locale.
toDateSpanCoerce an object to a DateSpan
toErrMetaMap an exception to its standard tags
toGridCoerce a value to a Grid
toHaystackCoerce a value to one of the Haystack types.
toIdCoerce a value to a Ref identifier
toIdsCoerce a value to a list of Ref identifiers
toRecCoerce a value to a record Dict
toRecsCoerce a value to a list of record Dicts
toSpanCoerce an object to a Span with optional timezone
toTagNameTake an arbitrary string and convert into a safe tag name.
unescapeTagNameUnescape 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:

  1. dis tag
  2. disMacro tag returns macro using dict as scope
  3. disKey maps to qname locale key
  4. name tag
  5. tag tag
  6. id tag
  7. 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 - z or _
  • 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, see Etc.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 itself
  • Date: one day range
  • Span: return Span.toDateSpan
  • Str: evaluates to DateSpan.fromStr
  • Date..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 date
  • Number: convert as year

toErrMeta ​

static Dict toErrMeta(Err e)

Map an exception to its standard tags:

  • dis: error display string
  • err: marker
  • errTrace: Str stack dump
  • axonTrace: 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 id tag
  • 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 id tag
  • Dict[] return id tags
  • Grid return id column

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 itself
  • Span+tz: update timezone using same dates only if aligned to midnight
  • Str: return Span.fromStr using current timezone
  • Str+tz: return Span.fromStr using given timezone
  • DateTime..DateTime: range of two DateTimes
  • Date..DateTime: start day for date until the end timestamp
  • DateTime..Date: start timestamp to end of day for end date
  • DateTime: span of a single timestamp
  • DateSpan: anything accepted by toDateSpan in current timezone
  • DateSpan+tz: anything accepted by toDateSpan using 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

makeConstruct 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

fromStrParse a query from string - see Filters for format.

Methods

equalsEquality is based on the normalized string.
hashHash is based on toStr.
matchesReturn if the specified record matches this filter.
toStrReturn 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

addColReturn a new grid with an additional column.
addColMetaReturn a new grid with additional column meta-data.
addColsReturn a new grid by adding the given grid as a new set of columns to this grid.
addMetaReturn a new grid with additional grid level meta-data.
allReturn true if the function returns true for all of the rows in the grid.
anyReturn true if the function returns true for any of the rows in the grid.
colGet a column by its name.
colDisNamesConvenience for cols mapped to Col.dis.
colNamesConvenience for cols mapped to Col.name.
colToListGet a column as a list of the cell values ordered by row.
colsColumns
colsToLocaleReturn a new Grid wich each col name mapped to its localized tag name if the col does not already have a display string.
commitReturn a new Grid which is the result of applying the given diffs to this grid.
eachIterate the rows
eachWhileIterate every row until the function returns non-null.
filterReturn a new grid which finds matching rows based on the given filter.
findFind one matching row or return null if no matches.
findAllReturn a new grid which finds matching the rows in this grid.
findIndexFind one matching row index or return null if no matches.
firstGet the first row or return null if grid is empty.
flatMapReturn a new grid which maps each of the rows to zero or more new Dicts.
getGet a row by its index number.
getRangeReturn a new grid which is a slice of the rows in this grid.
getSafeGet a row by its index number or if index is out of bounds then return null.
hasReturn if this grid contains the given column name.
isEmptyConvenience for size equal to zero.
isErrReturn if this is an error grid - meta has "err" tag.
isHisGridReturn if this grid conforms to the history grid shape
joinJoin two grids by column name.
keepColsReturn a new grid with all the columns removed except the given columns.
lastGet the last row or return null if grid is empty.
mapReturn a new grid which maps the rows to new Dict.
mapToListMap each row to a list of values.
metaMeta-data for entire grid
missingReturn if this grid does not contains the given column name.
removeColReturn a new grid with the given column removed.
removeColsReturn a new grid with all the given columns removed.
renameColReturn a new grid with the given column renamed.
renameColsReturn a new grid with multiple columns renamed.
reorderColsReturn a new grid with the columns reordered.
replaceReplace every cell with the given from value with the to value.
setColMetaReturn new grid with column meta-data replaced by given meta.
setMetaReturn a new grid with grid level meta-data replaced by given meta.
sizeGet the number of rows in the grid.
sortReturn a new Grid which is a copy of this grid with the rows sorted by the given comparator function.
sortColConvenience for sort which sorts the given column.
sortColrSort the given column in reverse.
sortDisSort using Etc.compareDis and Dict.dis.
sortrReturn a new Grid which is a copy of this grid with the rows reverse sorted by the given comparator function.
uniqueReturn 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.toGrid

Methods

addColAdd column to the grid.
addColNamesAdd list of column names to the grid.
addDictRowAdd dict as a new row to the grid.
addDictRowsConvience for adding a list of addDictRow.
addGridRowsAdd all the rows of given grid as rows to our grid
addRowAdd list of cells as a new row to the grid.
numColsNumber of columns added to the grid
numRowsNumber of rows added to the grid
setMetaSet the grid meta (overwrites any current meta) The meta parameter can be any Etc.makeDict value.
toGridConstruct 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

mConvenience for Marker.val

Methods

nConvenience for constructing a Number where unit may be either a Str name or a Unit instance.
verifyDictEqVerify two Dictts have same name/val pairs
verifyGridEqVerify that two grids are equal (meta, cols, and rows)
verifyGridIsEmptyVerify that given grid is empty (has no rows)
verifyListEqVerify contents of two lists using verifyValEq
verifyRefEqVerify two Refs are equal for both id and dis
verifyValEqVerify 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

makeConstruct timestamp/value pair.

Fields

tsTimestamp of the history record.
valValue at the timestamp.

Methods

compareOrdering is based on timestamp.
each
eachWhile
equalsEquality is based on timestamp and value.
get
has
hashHash 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

makeWrap input stream.

Fields

opts

Methods

readGridConvenience for readVal as Grid
readValRead 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])).readVal

opts ​

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

makeWrap output stream.

Fields

opts

Methods

closeClose the underlying output stream
flushFlush the underlying output stream and return this
valToStrGet a value as a JSON string.
writeGridWrite the grid and return this
writeValWrite 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).close

opts ​

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

fromStrParse a signature to its Kind representation.

Fields

nameName of kind: Bool, Number, List, etc
typeFantom type for the kind

Methods

equalsEquality is based signature
fromDefNameLookup Kind from its lower case def name
fromTypeLookup Kind for a Fantom type
fromValLookup Kind for a Fantom object
hashHash is based signature
toStrReturn 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

fromStrAlways return val

Fields

valSingleton value

Methods

fromBoolIf true return Marker.val else null
toStrReturn "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

fromStrAlways return val

Fields

valSingleton value

Methods

toStrReturn "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

defResolve 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

fromStrParse from a string according to zinc syntax
makeConstruct from scalar value and optional unit.
makeDurationConstruct from a duration, standardize unit is hours If unit is null, then a best attempt is made based on magnitude.
makeIntConstruct from scalar integer and optional unit.

Fields

defValDefault value is zero with no unit
nanConstant for not-a-number
negInfConstant for negative infinity
negOneConstant for -1 with no unit
oneConstant for 1 with no unit
posInfConstant for positive infinity
tenConstant for 10 with no unit
zeroConstant for 0 with no unit

Methods

absReturn absolute value of this number.
approxReturn if this number is approximately equal to that - see Float.approx
clampClamp this number between the min and max.
compareCompare is based on val.
decrementDecrement this number.
divDivide this by b.
equalsEquality is based on val and unit.
hashHash is based on val
incrementIncrement this number.
isDurationDoes this number have a time unit which can be converted to a Fantom Duration instance.
isIntIs this number a whole integer without a fractional part
isNaNIs the floating value NaN.
isNegativeIs this a negative number
isSpecialReturn if this number if pos/neg infinity or NaN
lowerGet the ASCII lower case version of this number as a Unicode point.
makeNumConstruct from scalar Int, Float, or Decimal and optional unit.
maxReturn max value.
minReturn min value.
minusSubtract b from this.
modReturn remainder of this divided by b.
multMultiple this and b.
negateNegate this number.
plusAdd this with b.
toCodeTrio/zinc code representation, same as toStr
toDurationGet this number as a Fantom Duration instance
toFloatGet the scalar value as an Float
toIntGet the scalar value as an Int
toLocaleFormat the number using given pattern which is an superset of Float.toLocale
toStrString representation
unitGet unit associated with this number or null.
upperGet 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:

  1. If isDuration true, then return best fit unit is selected
  2. If unit is non-null attempt to lookup a unit specific default pattern with the locale key "haystack::number.{unit.name}".
  3. If isInt true, then return Int.toLocale using sys locale default
  4. Return Float.toLocale using 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 sign

toStr ​

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

fromStrMake with simple id
makeConstruct with id string and optional display string.
makeWithDisConstruct with Ref id string and optional display string.

Fields

defValDefault is nullRef
nullRefNull ref is "@null"

Methods

disReturn display value of target if available, otherwise id
equalsEquality is based on id only (not dis).
genGenerate a unique Ref.
hashHash id
idIdentifier which does not include the leading @
isIdReturn if the string is a valid Ref identifier.
isIdCharIs the given character a valid id char
isNullNull ref has id value of "null"?
isSpecIs this a spec ref with double colons
toCodeReturn "@id"
toIdTake an arbitrary string and convert into a safe Ref identifier.
toStrString 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 - Z
  • a - z
  • 0 - 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

valSingleton value

Methods

toStrReturn "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

disGet display string for dict or the given tag.
eachIterate through all the columns.
eachWhileIterate through all the columns until function returns null, then break iteration and return the result.
getGet the column val by name.
gridParent grid
hasReturn true if the given name is mapped to a non-null column val.
isEmptyAlways returns false.
missingReturn true if the given name is not mapped to a non-null column val.
trapGet the column val by name.
valScalar 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

fromStrDecode from string format
makeAbsMake an absolute span for two date times which must be defined in the Rel timezone
makeDateMake an absolute span for the given date
makeRelMake a relative span for given mode using current time and current locale for starting weekday

Fields

endExclusive ending timestamp
modeAbsolute or relative mode
startInclusive starting timestamp

Methods

disDisplay string for current locale
equalsEquality is based on mode only for relative, start/end for abs
hashHash code is based on mode only for relative, start/end for abs
toCodeReturn axon representation for this span.
toDateSpanConvert this span to a DateSpan attempting to use aligned dates
toStrEncode to string, see fromStr
toTimeZoneConvert to timezone using DateTime.toTimeZone on both start, end
todayConvenience for Span(SpanMode.today)
tzTimezone 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 SpanMode mode 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

fromStrReturn the SpanMode instance for the specified name.

Fields

valsList of SpanMode values indexed by ordinal

Methods

disDisplay name for relative period
isAbsIs this an absolute mode
isRelIs 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

fromStrConstruct from string

Methods

equalsEquality is based on string representation
hashHash code is based on string representation
nameSimple name
toCodeCode representation with leading "^" caret.
toStrString 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

makeWrap input stream

Methods

eachDictIterate through the entire stream reading dicts.
readAllDictsRead all dicts from the stream and close it.
readDictRead next dict from the stream.
readGridReturn 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

makeWrap output stream

Methods

closeClose the underlying output stream
writeAllDictsWrite the list of dicts.
writeDictWrite separator and record.
writeGridWrite 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:

  1. Create subclass of TypedDict
  2. Annotate const instance fields with @TypedTag
  3. Create constructor with Dict and it-block callback
  4. 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

makeSub constructor.

Methods

createFactory to create for given type and dict to wrap.
eachIterate the wrapped dict tags
eachWhileIterate the wrapped dict tags until callback returns non-null
getGet a tag from wrapped dict
hasReturn if wrapped dict has given tag
isEmptyReturn if wrapped dict is empty
metaWrapped dict for this instance
missingReturn if wrapped dict is missing given tag
trapTrap 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

metaMeta 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

makeConstruct 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

makeConstruct 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

makeConstruct 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

makeConstruct for type name and string value

Fields

typeType name
valString value

Methods

decodeDecode into its appropiate Fantom type or fallback to generic XStr
equalsEquality is base on type and val
hashHash 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

makeWrap input stream

Methods

closeClose the underlying stream.
readGridConvenience for readVal as Grid
readValRead 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

makeWrap given output strea

Methods

closeClose underlying stream
flushFlush underlying stream
gridToStrFormat a grid to a zinc string in memory.
valToStrGet a value as a zinc string.
writeGridWrite a grid to stream
writeValWrite 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