lattice-grid 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE +21 -0
  3. data/README.md +179 -0
  4. data/lib/lattice/grid/aggregate_sql.rb +98 -0
  5. data/lib/lattice/grid/cells.rb +85 -0
  6. data/lib/lattice/grid/collab/axis.rb +40 -0
  7. data/lib/lattice/grid/collab/channel.rb +31 -0
  8. data/lib/lattice/grid/collab/channel_handler.rb +84 -0
  9. data/lib/lattice/grid/collab/connection.rb +72 -0
  10. data/lib/lattice/grid/collab/doc_model.rb +99 -0
  11. data/lib/lattice/grid/collab/doc_model_apply.rb +105 -0
  12. data/lib/lattice/grid/collab/doc_model_doc.rb +95 -0
  13. data/lib/lattice/grid/collab/doc_model_normalize.rb +120 -0
  14. data/lib/lattice/grid/collab/doc_server.rb +84 -0
  15. data/lib/lattice/grid/collab/doc_server_messages.rb +129 -0
  16. data/lib/lattice/grid/collab/iron_calc.rb +84 -0
  17. data/lib/lattice/grid/collab/iron_calc_ops.rb +118 -0
  18. data/lib/lattice/grid/collab/iron_calc_sheets.rb +69 -0
  19. data/lib/lattice/grid/collab/memory_store.rb +63 -0
  20. data/lib/lattice/grid/collab/refs.rb +131 -0
  21. data/lib/lattice/grid/collab/refs_shrink.rb +56 -0
  22. data/lib/lattice/grid/collab/wasm_book.rb +97 -0
  23. data/lib/lattice/grid/collab/wire.rb +135 -0
  24. data/lib/lattice/grid/collab/wire_model_ops.rb +33 -0
  25. data/lib/lattice/grid/collab/wire_ops.rb +120 -0
  26. data/lib/lattice/grid/collab/wire_style.rb +60 -0
  27. data/lib/lattice/grid/collab.rb +44 -0
  28. data/lib/lattice/grid/context.rb +82 -0
  29. data/lib/lattice/grid/dates.rb +76 -0
  30. data/lib/lattice/grid/filter_sql.rb +87 -0
  31. data/lib/lattice/grid/json.rb +60 -0
  32. data/lib/lattice/grid/keyset.rb +49 -0
  33. data/lib/lattice/grid/kind.rb +58 -0
  34. data/lib/lattice/grid/levels.rb +121 -0
  35. data/lib/lattice/grid/limits.rb +51 -0
  36. data/lib/lattice/grid/pager.rb +118 -0
  37. data/lib/lattice/grid/parser/filter_rules.rb +119 -0
  38. data/lib/lattice/grid/parser/group_rules.rb +105 -0
  39. data/lib/lattice/grid/parser/request_rules.rb +131 -0
  40. data/lib/lattice/grid/parser/tree_rules.rb +68 -0
  41. data/lib/lattice/grid/parser.rb +126 -0
  42. data/lib/lattice/grid/pivot_sql.rb +78 -0
  43. data/lib/lattice/grid/query.rb +76 -0
  44. data/lib/lattice/grid/request.rb +19 -0
  45. data/lib/lattice/grid/respond.rb +60 -0
  46. data/lib/lattice/grid/sql.rb +103 -0
  47. data/lib/lattice/grid/tree_sql.rb +59 -0
  48. data/lib/lattice/grid/values.rb +124 -0
  49. data/lib/lattice/grid/version.rb +7 -0
  50. data/lib/lattice/grid.rb +29 -0
  51. data/wasm/ironcalc_wasi.wasm +0 -0
  52. metadata +110 -0
@@ -0,0 +1,60 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Lattice
6
+ module Grid
7
+ # JSON that agrees with JavaScript.
8
+ module Json
9
+ # One escape: a surrogate pair, a lone surrogate, or any other escape.
10
+ ESCAPE = /\\(?:u[dD][89abAB]\h{2}\\u[dD][c-fC-F]\h{2}|(u[dD][89a-fA-F]\h{2})|.)/m
11
+ NUMBER = /\A(\d+)\.(\d+)(?:e([+-]\d+))?\z/
12
+
13
+ module_function
14
+
15
+ # JSON.parse raises on a lone surrogate escape such as `\ud800`, which JavaScript accepts.
16
+ # The escape becomes U+0000, so the parser rejects the string with `bad_string`, as for NUL.
17
+ def parse(text, **)
18
+ JSON.parse(text.gsub(ESCAPE) { Regexp.last_match(1) ? "\\u0000" : Regexp.last_match(0) }, **)
19
+ end
20
+
21
+ # Compact JSON with numbers as JavaScript writes them (`1e-7`, `1` for 1.0).
22
+ # A pivot field is this JSON, so it must be the same in every server.
23
+ def generate(value)
24
+ case value
25
+ when Array then "[#{value.map { |v| generate(v) }.join(',')}]"
26
+ when Float then number(value)
27
+ else JSON.generate(value)
28
+ end
29
+ end
30
+
31
+ def number(float)
32
+ return "0" if float.zero?
33
+ return "-#{number(-float)}" if float.negative?
34
+
35
+ format_digits(*digits(float))
36
+ end
37
+
38
+ # The significant digits of a positive Float, and the place of the decimal point after the first digit.
39
+ def digits(float)
40
+ whole, fraction, exponent = NUMBER.match(float.to_s).captures
41
+ all = whole + fraction
42
+ lead = all[/\A0*/].size
43
+ [all[lead..].sub(/0+\z/, ""), whole.size + exponent.to_i - lead]
44
+ end
45
+
46
+ # The steps of Number::toString in ECMA-262: the value is 0.digits times 10 to the power of `point`.
47
+ def format_digits(digits, point)
48
+ return digits + ("0" * (point - digits.size)) if point.between?(digits.size, 21)
49
+ return "#{digits[0, point]}.#{digits[point..]}" if point.between?(1, 21)
50
+ return "0.#{'0' * -point}#{digits}" if point.between?(-5, 0)
51
+
52
+ exponent(digits, point - 1)
53
+ end
54
+
55
+ def exponent(digits, power)
56
+ "#{digits[0]}#{".#{digits[1..]}" if digits.size > 1}e#{power.negative? ? '-' : '+'}#{power.abs}"
57
+ end
58
+ end
59
+ end
60
+ end
@@ -0,0 +1,49 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lattice
4
+ module Grid
5
+ # Keyset conditions. A key is `[name, dir, nulls]`; `at` is the decoded cursor tuple.
6
+ # Nulls go first or last in both directions, as in the reference evaluator.
7
+ module Keyset
8
+ module_function
9
+
10
+ # The rows strictly after `at` in the order of `keys`: equal on the first keys, then after on one.
11
+ def after(sql, keys, at, table)
12
+ terms = keys.each_index.filter_map do |i|
13
+ step = step(sql, keys[i], at[i], table)
14
+ Arel::Nodes::Grouping.new(Arel::Nodes::And.new(equal(sql, keys.first(i), at, table) + [step])) if step
15
+ end
16
+ terms.reduce { |a, b| a.or(b) } || Sql::NEVER
17
+ end
18
+
19
+ # The rows strictly before `at`.
20
+ def before(sql, keys, at, table)
21
+ after(sql, reverse(keys), at, table)
22
+ end
23
+
24
+ # The rows at `at` or after it.
25
+ def at_or_after(sql, keys, at, table)
26
+ after(sql, keys, at, table).or(Arel::Nodes::And.new(equal(sql, keys, at, table)))
27
+ end
28
+
29
+ def equal(sql, keys, at, table)
30
+ keys.each_with_index.map { |(name), i| sql.equal(name, at[i], table) }
31
+ end
32
+
33
+ def reverse(keys)
34
+ keys.map { |name, dir, nulls| [name, dir == "asc" ? "desc" : "asc", nulls == "first" ? "last" : "first"] }
35
+ end
36
+
37
+ # The rows after `value` on one key, or nil when no row comes after it.
38
+ def step(sql, key, value, table)
39
+ name, dir, nulls = key
40
+ return (table[name].not_eq(nil) if nulls == "first") if value.nil?
41
+
42
+ node = sql.ordered(name, table)
43
+ bound = sql.value(name, value)
44
+ cmp = dir == "asc" ? node.gt(bound) : node.lt(bound)
45
+ nulls == "last" ? cmp.or(table[name].eq(nil)) : cmp
46
+ end
47
+ end
48
+ end
49
+ end
@@ -0,0 +1,58 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lattice
4
+ module Grid
5
+ # Type checks that never raise. `case value when klass` calls `klass === value`, which works also on
6
+ # a BasicObject, where `value.is_a?` does not exist.
7
+ module Kind
8
+ MAX_SAFE = (2**53) - 1
9
+
10
+ module_function
11
+
12
+ def of?(value, klass)
13
+ case value
14
+ when klass then true
15
+ else false
16
+ end
17
+ end
18
+
19
+ def string?(value)
20
+ of?(value, String)
21
+ end
22
+
23
+ def boolean?(value)
24
+ true.equal?(value) || false.equal?(value)
25
+ end
26
+
27
+ # U+0000, or a lone surrogate. In Ruby a lone surrogate is invalid UTF-8.
28
+ def bad_string?(value)
29
+ return true unless value.valid_encoding?
30
+ return true unless value.encoding == Encoding::UTF_8 || value.ascii_only?
31
+
32
+ value.include?("\u0000")
33
+ end
34
+
35
+ # The length in UTF-16 code units, as in JavaScript.
36
+ def js_length(value)
37
+ return value.size if value.ascii_only?
38
+ return value.bytesize unless value.valid_encoding?
39
+
40
+ value.encode("UTF-16LE").bytesize / 2
41
+ end
42
+
43
+ # A JSON number, or nil. An integer that JavaScript cannot hold exactly becomes a Float.
44
+ def number(value)
45
+ case value
46
+ when Integer then value.abs > MAX_SAFE ? value.to_f : value
47
+ when Float then value if value.finite?
48
+ end
49
+ end
50
+
51
+ # Number.isSafeInteger: an Integer, or a whole Float, within 2**53 - 1.
52
+ def safe_int(value)
53
+ value = value.to_i if of?(value, Float) && value.finite? && value == value.floor
54
+ value if of?(value, Integer) && value.abs <= MAX_SAFE
55
+ end
56
+ end
57
+ end
58
+ end
@@ -0,0 +1,121 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lattice
4
+ module Grid
5
+ # Leaf rows. `rows` gives [row, sort tuple] pairs; the tuple comes from the full row, not the projection.
6
+ class LeafLevel
7
+ def initialize(context)
8
+ @context = context
9
+ @sql = context.sql
10
+ end
11
+
12
+ def keys
13
+ @context.leaf_keys
14
+ end
15
+
16
+ def page
17
+ Pager.new(@context, self).page
18
+ end
19
+
20
+ def count
21
+ @context.base.count
22
+ end
23
+
24
+ def rows(cond, order, limit, offset)
25
+ rel = @context.base.select(*selects(order))
26
+ rel = rel.where(cond.call(@sql.table)) if cond
27
+ rel = rel.reorder(*order.map { |key| @sql.order(*key) }).limit(limit).offset(offset)
28
+ @context.select_all(rel).map { |row| [cells(row), tuple(row, order)] }
29
+ end
30
+
31
+ private
32
+
33
+ # The projection. The key column is always in the row.
34
+ def names
35
+ columns = @context.request.columns
36
+ columns ? ([@context.key].compact + columns).uniq : @context.columns.map(&:name)
37
+ end
38
+
39
+ def selects(order)
40
+ names.each_with_index.map { |n, i| @sql.table[n].as("c#{i}") } +
41
+ order.each_with_index.map { |(n), i| @sql.table[n].as("s#{i}") } + tree_count
42
+ end
43
+
44
+ def tree_count
45
+ @context.tree ? [@context.tree.count.as("n")] : []
46
+ end
47
+
48
+ # Tree data adds the child count after the projection.
49
+ def cells(row)
50
+ out = names.each_with_index.to_h { |n, i| [n, @context.cells.cell(n, row["c#{i}"])] }
51
+ out[GROUP_COUNT_KEY] = Integer(row["n"]) if @context.tree
52
+ out
53
+ end
54
+
55
+ def tuple(row, order)
56
+ order.each_with_index.map { |(n), i| @context.cells.cell(n, row["s#{i}"]) }
57
+ end
58
+ end
59
+
60
+ # Group rows for the column `group.by[keys.length]`, sorted by that column.
61
+ class GroupLevel
62
+ def initialize(context, aggregates)
63
+ @context = context
64
+ @sql = context.sql
65
+ @aggregates = aggregates
66
+ @name = context.request.group.by[context.request.group.keys.size]
67
+ end
68
+
69
+ def keys
70
+ item = @context.request.sort.find { |s| s.column == @name }
71
+ [[@name, item&.dir || "asc", item&.nulls || "last"]]
72
+ end
73
+
74
+ def page
75
+ Pager.new(@context, self).page
76
+ end
77
+
78
+ # The number of groups, with the null group.
79
+ def count
80
+ column = @sql.table[@name]
81
+ @context.model.unscoped.from(@context.base.select(column).group(column), "lattice_groups").count
82
+ end
83
+
84
+ def rows(cond, order, limit, offset)
85
+ rel = grouped
86
+ rel = rel.where(cond.call(AggregateSql::ROWS)) if cond
87
+ rel = rel.reorder(*order.map { |key| @sql.order(*key, AggregateSql::ROWS) }).limit(limit).offset(offset)
88
+ @context.select_all(rel).map { |row| group_row(row) }
89
+ end
90
+
91
+ private
92
+
93
+ def grouped
94
+ column = AggregateSql::ROWS[@name]
95
+ @aggregates.relation([@name]).select(column.as("g"), *@aggregates.selects).group(column)
96
+ end
97
+
98
+ def group_row(row)
99
+ value = @context.cells.cell(@name, row["g"])
100
+ [{ @name => value }.merge(@aggregates.cells(row)), [value]]
101
+ end
102
+ end
103
+
104
+ # A pivot at the leaf level: one aggregate row.
105
+ class PivotRow
106
+ def initialize(context, aggregates)
107
+ @context = context
108
+ @aggregates = aggregates
109
+ end
110
+
111
+ def count
112
+ 1
113
+ end
114
+
115
+ def page
116
+ row = @context.select_all(@aggregates.relation([]).select(*@aggregates.selects)).first
117
+ MemoryPager.new(@context).page([@aggregates.cells(row)])
118
+ end
119
+ end
120
+ end
121
+ end
@@ -0,0 +1,51 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lattice
4
+ # The protocol constants and the rules that they share.
5
+ module Grid
6
+ # Hard limits on a request. They are the same as LIMITS in packages/protocol/src/limits.ts.
7
+ LIMITS = {
8
+ maxFilterDepth: 16,
9
+ maxFilterNodes: 256,
10
+ maxFilterValues: 1000,
11
+ maxList: 1000,
12
+ maxSort: 16,
13
+ maxGroupBy: 16,
14
+ maxPage: 10_000,
15
+ maxString: 1024,
16
+ maxSearch: 256,
17
+ maxCursor: 4096,
18
+ maxPivotValues: 200,
19
+ maxTreeDepth: 16,
20
+ maxErrors: 50
21
+ }.freeze
22
+
23
+ FILTER_OPS = %w[eq ne lt lte gt gte in notIn contains startsWith endsWith blank notBlank between inRange]
24
+ .map(&:freeze).freeze
25
+ AGGREGATE_FNS = %w[sum avg min max count first last].map(&:freeze).freeze
26
+ COLUMN_TYPES = %w[string number boolean date].map(&:freeze).freeze
27
+ GROUP_COUNT_KEY = "$count"
28
+ TREE_PATH_SEPARATOR = "/"
29
+ RESERVED_NAMES = %w[__proto__ constructor prototype].freeze
30
+ IDENTIFIER = /\A[A-Za-z_][A-Za-z0-9_]*\z/
31
+
32
+ SCALAR_OPS = %w[eq ne lt lte gt gte contains startsWith endsWith].freeze
33
+ TEXT_OPS = %w[contains startsWith endsWith].freeze
34
+ ORDER_OPS = %w[lt lte gt gte between].freeze
35
+
36
+ module_function
37
+
38
+ # True when the op makes sense for the column type.
39
+ def op_fits_type?(operator, type)
40
+ return type == "string" if TEXT_OPS.include?(operator)
41
+ return type == "date" if operator == "inRange"
42
+ return type != "boolean" if ORDER_OPS.include?(operator)
43
+
44
+ true
45
+ end
46
+
47
+ def aggregate_fits_type?(function, type)
48
+ %w[sum avg].include?(function) ? type == "number" : true
49
+ end
50
+ end
51
+ end
@@ -0,0 +1,118 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lattice
4
+ module Grid
5
+ # One page of output rows. `tuples` are the sort values of each row, for cursors. `known` is the row
6
+ # count when the page knows it. `more` and `before` tell if rows come after and before the page.
7
+ Page = Struct.new(:rows, :tuples, :cursor, :last, :known, :more, :before, keyword_init: true)
8
+
9
+ # Offset or keyset paging over a level. The level gives `keys`, and `rows(cond, order, limit, offset)`
10
+ # as [row, tuple] pairs. It fetches one more row than the page to find the next page.
11
+ class Pager
12
+ def initialize(context, level)
13
+ @context = context
14
+ @sql = context.sql
15
+ @level = level
16
+ @keys = level.keys
17
+ @range = context.request.range
18
+ end
19
+
20
+ def page
21
+ return offset_page if @range.is_a?(OffsetRange)
22
+
23
+ at = cursor_tuple
24
+ page = @range.before ? before_page(at) : after_page(at)
25
+ page.cursor = cursor(page)
26
+ page
27
+ end
28
+
29
+ private
30
+
31
+ def cursor_tuple
32
+ cursor = @range.after || @range.before
33
+ path = @range.after ? "range.after" : "range.before"
34
+ cursor && @context.cells.decode(cursor, @keys.map(&:first), path)
35
+ end
36
+
37
+ def cursor(page)
38
+ out = {}
39
+ return out if page.rows.empty?
40
+
41
+ out[:next] = @context.cells.encode(page.tuples.last) if page.more
42
+ out[:prev] = @context.cells.encode(page.tuples.first) if page.before
43
+ out
44
+ end
45
+
46
+ def offset_page
47
+ size = @range.end - @range.start
48
+ got = @level.rows(nil, @keys, size + 1, @range.start)
49
+ last = got.size <= size
50
+ Page.new(rows: got.first(size).map(&:first), last: last, known: (offset_count(got) if last))
51
+ end
52
+
53
+ # On the last page the count is start + rows, unless the page is empty after the start.
54
+ def offset_count(got)
55
+ @range.start + got.size if got.any? || @range.start.zero?
56
+ end
57
+
58
+ def after_page(at)
59
+ cond = at && ->(table) { Keyset.after(@sql, @keys, at, table) }
60
+ got = @level.rows(cond, @keys, @range.limit + 1, 0)
61
+ more = got.size > @range.limit
62
+ pairs = got.first(@range.limit)
63
+ known = pairs.size unless at || more
64
+ page_of(pairs, more: more, before: before?(at, pairs), last: !more, known: known)
65
+ end
66
+
67
+ def before?(at, pairs)
68
+ at && pairs.any? && @context.exists?(Keyset.before(@sql, @keys, pairs.first.last, @sql.table))
69
+ end
70
+
71
+ def before_page(at)
72
+ cond = ->(table) { Keyset.before(@sql, @keys, at, table) }
73
+ got = @level.rows(cond, Keyset.reverse(@keys), @range.limit + 1, 0)
74
+ beyond = @context.exists?(Keyset.at_or_after(@sql, @keys, at, @sql.table))
75
+ page_of(got.first(@range.limit).reverse, more: beyond, before: got.size > @range.limit, last: !beyond)
76
+ end
77
+
78
+ def page_of(pairs, **flags)
79
+ Page.new(rows: pairs.map(&:first), tuples: pairs.map(&:last), **flags)
80
+ end
81
+ end
82
+
83
+ # Paging over rows in memory, as the reference evaluator does: the one row of a pivot at the leaf
84
+ # level. Its sort tuple is empty.
85
+ class MemoryPager
86
+ def initialize(context)
87
+ @context = context
88
+ @range = context.request.range
89
+ end
90
+
91
+ def page(rows)
92
+ from, to = bounds(rows.size)
93
+ Page.new(rows: rows[from...to], cursor: cursor(from, to, rows.size), last: to >= rows.size, known: rows.size)
94
+ end
95
+
96
+ private
97
+
98
+ def bounds(size)
99
+ return [@range.start, @range.end].map { |i| [i, size].min } if @range.is_a?(OffsetRange)
100
+
101
+ cursor = @range.after || @range.before
102
+ return [0, [@range.limit, size].min] unless cursor
103
+
104
+ @context.cells.decode(cursor, [], @range.after ? "range.after" : "range.before")
105
+ @range.after ? [size, size] : [0, 0]
106
+ end
107
+
108
+ def cursor(from, to, size)
109
+ return if @range.is_a?(OffsetRange)
110
+
111
+ out = {}
112
+ out[:next] = @context.cells.encode([]) if to < size && to > from
113
+ out[:prev] = @context.cells.encode([]) if from.positive? && to > from
114
+ out
115
+ end
116
+ end
117
+ end
118
+ end
@@ -0,0 +1,119 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lattice
4
+ module Grid
5
+ # The rules for the filter tree.
6
+ class Parser
7
+ private
8
+
9
+ def filter(input, path, depth)
10
+ return NONE if @stopped
11
+ return NONE unless room?(path, depth)
12
+
13
+ hash = rec(input)
14
+ return err(path, "invalid", "must be an object") unless hash
15
+
16
+ op = get(hash, "op")
17
+ return logic(input, hash, path, depth) if pick(op, %w[and or])
18
+ return negation(input, hash, path, depth) if pick(op, %w[not])
19
+
20
+ leaf(input, hash, path)
21
+ end
22
+
23
+ # The depth check, then the node count, before the node is read.
24
+ def room?(path, depth)
25
+ if depth > LIMITS[:maxFilterDepth]
26
+ stop(path, "too_deep", "filter depth is at most #{LIMITS[:maxFilterDepth]}")
27
+ return false
28
+ end
29
+ @nodes += 1
30
+ return true if @nodes <= LIMITS[:maxFilterNodes]
31
+
32
+ stop("filter", "too_long", "at most #{LIMITS[:maxFilterNodes]} filter nodes")
33
+ false
34
+ end
35
+
36
+ def stop(path, code, message)
37
+ @stopped = true
38
+ err(path, code, message)
39
+ end
40
+
41
+ def logic(input, hash, path, depth)
42
+ obj(input, path, %w[op nodes])
43
+ nodes = list(get(hash, "nodes"), "#{path}.nodes", LIMITS[:maxList], 1)
44
+ return NONE if none?(nodes)
45
+
46
+ out = children(nodes, path, depth)
47
+ out.size == nodes.size ? Logic.new(op: pick(hash["op"], %w[and or]), nodes: out.freeze) : NONE
48
+ end
49
+
50
+ def children(nodes, path, depth)
51
+ out = []
52
+ nodes.each_with_index do |node, i|
53
+ break if @stopped
54
+
55
+ child = filter(node, "#{path}.nodes[#{i}]", depth + 1)
56
+ out << child unless none?(child)
57
+ end
58
+ out
59
+ end
60
+
61
+ def negation(input, hash, path, depth)
62
+ obj(input, path, %w[op node])
63
+ node = filter(get(hash, "node"), "#{path}.node", depth + 1)
64
+ none?(node) ? NONE : Not.new(op: "not", node: node)
65
+ end
66
+
67
+ def leaf(input, hash, path)
68
+ op = pick(get(hash, "op"), FILTER_OPS)
69
+ return unknown_op(input, path) unless op
70
+
71
+ blank = %w[blank notBlank].include?(op)
72
+ obj(input, path, blank ? %w[column op] : %w[column op value])
73
+ col = leaf_column(get(hash, "column"), op, path)
74
+ return NONE if none?(col)
75
+ return Leaf.new(column: col.name, op: op, value: nil) if blank
76
+
77
+ value = leaf_value(get(hash, "value"), op, col, "#{path}.value")
78
+ none?(value) ? NONE : Leaf.new(column: col.name, op: op, value: value)
79
+ end
80
+
81
+ def unknown_op(input, path)
82
+ obj(input, path, %w[column op value])
83
+ err("#{path}.op", "invalid", "unknown op")
84
+ end
85
+
86
+ def leaf_column(input, operator, path)
87
+ col = column(input, "#{path}.column")
88
+ return col if none?(col) || (col.filter.include?(operator) && Grid.op_fits_type?(operator, col.type))
89
+
90
+ err("#{path}.op", "op_not_allowed", %(op "#{operator}" is not allowed on "#{col.name}"))
91
+ end
92
+
93
+ def leaf_value(raw, operator, col, path)
94
+ return scalar(raw, col.type, path) if SCALAR_OPS.include?(operator)
95
+
96
+ items = value_list(raw, operator, path)
97
+ return NONE if none?(items) || !values_room?(items, path)
98
+
99
+ values = items.each_with_index.map { |v, i| scalar(v, col.type, "#{path}[#{i}]") }
100
+ none?(*values) ? NONE : values.freeze
101
+ end
102
+
103
+ # `in` and `notIn` take 1 to maxList values; `between` and `inRange` take 2.
104
+ def value_list(raw, operator, path)
105
+ return list(raw, path, LIMITS[:maxList], 1) if %w[in notIn].include?(operator)
106
+
107
+ list(raw, path, 2, 2)
108
+ end
109
+
110
+ def values_room?(items, path)
111
+ @values += items.size
112
+ return true if @values <= LIMITS[:maxFilterValues]
113
+
114
+ stop(path, "too_long", "at most #{LIMITS[:maxFilterValues]} values in one filter")
115
+ false
116
+ end
117
+ end
118
+ end
119
+ end
@@ -0,0 +1,105 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lattice
4
+ module Grid
5
+ # The rules for groups, aggregates and the pivot.
6
+ class Parser
7
+ private
8
+
9
+ def group(input)
10
+ hash = obj(input, "group", %w[by keys])
11
+ return NONE if none?(hash)
12
+
13
+ by = group_columns(get(hash, "by"), "group.by")
14
+ keys = list(get(hash, "keys"), "group.keys", LIMITS[:maxGroupBy])
15
+ return NONE if none?(by, keys)
16
+ return err("group.keys", "too_many_keys", "keys.length must be at most by.length") if keys.size > by.size
17
+
18
+ group_keys(by, keys)
19
+ end
20
+
21
+ def group_keys(by, keys)
22
+ out = keys.each_with_index.map do |k, i|
23
+ scalar(k, @columns.fetch(by[i]).type, "group.keys[#{i}]", nullable: true)
24
+ end
25
+ none?(*out) ? NONE : Group.new(by: by, keys: out.freeze)
26
+ end
27
+
28
+ def group_columns(input, path)
29
+ items = list(input, path, LIMITS[:maxGroupBy])
30
+ return NONE if none?(items)
31
+
32
+ out = items.each_with_index.filter_map { |item, i| group_column(item, "#{path}[#{i}]") }
33
+ out.size == items.size ? out.freeze : NONE
34
+ end
35
+
36
+ def group_column(item, path)
37
+ col = column(item, path)
38
+ return if none?(col)
39
+ return col.name if col.group
40
+
41
+ err(path, "not_groupable", %(cannot group by "#{col.name}")) && nil
42
+ end
43
+
44
+ def aggregates(input, path, taken)
45
+ items = list(input, path, LIMITS[:maxList])
46
+ return NONE if none?(items)
47
+
48
+ used = Set.new([*taken, GROUP_COUNT_KEY])
49
+ out = items.each_with_index.filter_map { |item, i| aggregate(item, "#{path}[#{i}]", used) }
50
+ out.size == items.size ? out.freeze : NONE
51
+ end
52
+
53
+ def aggregate(item, path, used)
54
+ hash = obj(item, path, %w[column fn as])
55
+ return if none?(hash)
56
+
57
+ col = column(get(hash, "column"), "#{path}.column")
58
+ fn = pick(get(hash, "fn"), AGGREGATE_FNS)
59
+ return err("#{path}.fn", "invalid", "unknown aggregate fn") && nil unless fn
60
+ return if none?(col) || !aggregate_allowed?(col, fn, path)
61
+
62
+ agg = output_name(hash, Aggregate.new(column: col.name, fn: fn, as: nil), path)
63
+ unique(agg, path, used) if agg
64
+ end
65
+
66
+ def aggregate_allowed?(col, function, path)
67
+ return true if col.aggregate.include?(function) && Grid.aggregate_fits_type?(function, col.type)
68
+
69
+ err("#{path}.fn", "aggregate_not_allowed", %("#{function}" is not allowed on "#{col.name}"))
70
+ false
71
+ end
72
+
73
+ # The aggregate with its `as`, or nil when `as` is bad.
74
+ def output_name(hash, agg, path)
75
+ return agg unless hash.key?("as")
76
+
77
+ as = hash["as"]
78
+ return nul("#{path}.as") && nil if Kind.string?(as) && Kind.bad_string?(as)
79
+ return agg.with(as: String.new(as).freeze) if identifier?(as)
80
+
81
+ err("#{path}.as", "invalid", "must be an identifier of at most 64 characters") && nil
82
+ end
83
+
84
+ def identifier?(value)
85
+ Kind.string?(value) && value.size <= 64 && IDENTIFIER.match?(value) && !RESERVED_NAMES.include?(value)
86
+ end
87
+
88
+ def unique(agg, path, used)
89
+ return err("#{path}.as", "invalid", %(duplicate output key "#{agg.key}")) && nil if used.include?(agg.key)
90
+
91
+ used << agg.key
92
+ agg
93
+ end
94
+
95
+ def pivot(input)
96
+ hash = obj(input, "pivot", %w[by values])
97
+ return NONE if none?(hash)
98
+
99
+ by = group_columns(get(hash, "by"), "pivot.by")
100
+ values = aggregates(get(hash, "values"), "pivot.values", [])
101
+ none?(by, values) ? NONE : Pivot.new(by: by, values: values)
102
+ end
103
+ end
104
+ end
105
+ end