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,131 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lattice
4
+ module Grid
5
+ # The rules for the request, the range and the sort.
6
+ class Parser
7
+ REQUEST_KEYS = %w[v range sort filter search group aggregate pivot columns count tree].freeze
8
+
9
+ # The request, or NONE.
10
+ def request(input)
11
+ hash = obj(input, "", REQUEST_KEYS)
12
+ return NONE if none?(hash)
13
+
14
+ version(get(hash, "v"))
15
+ parts = required_parts(hash)
16
+ optional = optional_parts(hash)
17
+ optional[:tree] = tree_part(hash, parts, optional)
18
+ return NONE if none?(*parts.values)
19
+
20
+ Request.new(v: 1, **parts, **optional)
21
+ end
22
+
23
+ private
24
+
25
+ def version(value)
26
+ err("v", "invalid", "must be 1") unless (Kind.of?(value, Integer) || Kind.of?(value, Float)) && value == 1
27
+ end
28
+
29
+ def required_parts(hash)
30
+ range = range(get(hash, "range"))
31
+ sort = sort(get(hash, "sort"))
32
+ raw = get(hash, "filter")
33
+ filter = raw.nil? ? nil : filter(raw, "filter", 1)
34
+ group = group(get(hash, "group"))
35
+ aggregate = aggregates(get(hash, "aggregate"), "aggregate", none?(group) ? [] : group.by)
36
+ { range: range, sort: sort, filter: filter, group: group, aggregate: aggregate }
37
+ end
38
+
39
+ def optional_parts(hash)
40
+ search = hash.key?("search") ? str(hash["search"], "search", LIMITS[:maxSearch]) : nil
41
+ pivot = hash.key?("pivot") ? pivot(hash["pivot"]) : nil
42
+ parts = { search: search, pivot: pivot, columns: projection(hash), count: count(hash) }
43
+ parts.transform_values { |v| none?(v) ? nil : v }
44
+ end
45
+
46
+ def projection(hash)
47
+ return unless hash.key?("columns")
48
+
49
+ items = list(hash["columns"], "columns", LIMITS[:maxList])
50
+ return NONE if none?(items)
51
+
52
+ columns = items.each_with_index.map { |c, i| column(c, "columns[#{i}]") }
53
+ columns.reject { |c| none?(c) }.map(&:name).freeze
54
+ end
55
+
56
+ def count(hash)
57
+ return unless hash.key?("count")
58
+
59
+ value = hash["count"]
60
+ Kind.boolean?(value) ? value : err("count", "invalid", "must be a boolean")
61
+ end
62
+
63
+ def range(input)
64
+ hash = rec(input)
65
+ return offset_range(input, hash) if hash && (hash.key?("start") || hash.key?("end"))
66
+
67
+ hash = obj(input, "range", %w[after before limit])
68
+ return NONE if none?(hash)
69
+
70
+ limit = Kind.safe_int(get(hash, "limit"))
71
+ return cursor_range(hash, limit) if limit&.between?(1, LIMITS[:maxPage])
72
+
73
+ err("range.limit", "bad_range", "needs an integer from 1 to #{LIMITS[:maxPage]}")
74
+ end
75
+
76
+ def offset_range(input, hash)
77
+ obj(input, "range", %w[start end])
78
+ start = Kind.safe_int(get(hash, "start"))
79
+ stop = Kind.safe_int(get(hash, "end"))
80
+ unless start && stop && start >= 0 && stop >= start
81
+ return err("range", "bad_range", "needs integers with 0 <= start <= end")
82
+ end
83
+ return err("range", "bad_range", "at most #{LIMITS[:maxPage]} rows") if stop - start > LIMITS[:maxPage]
84
+
85
+ OffsetRange.new(start: start, end: stop)
86
+ end
87
+
88
+ def cursor_range(hash, limit)
89
+ return err("range", "bad_range", "use after or before, not both") if hash.key?("after") && hash.key?("before")
90
+ return err("range", "bad_range", "cursor paging needs a key column") unless @key
91
+
92
+ cursors = %w[after before].select { |k| hash.key?(k) }.to_h do |k|
93
+ [k.to_sym, str(hash[k], "range.#{k}", LIMITS[:maxCursor])]
94
+ end
95
+ return NONE if none?(*cursors.values)
96
+
97
+ CursorRange.new(after: nil, before: nil, limit: limit, **cursors)
98
+ end
99
+
100
+ def sort(input)
101
+ items = list(input, "sort", LIMITS[:maxSort])
102
+ return NONE if none?(items)
103
+
104
+ items.each_with_index.filter_map { |item, i| sort_item(item, "sort[#{i}]") }.freeze
105
+ end
106
+
107
+ def sort_item(item, path)
108
+ hash = obj(item, path, %w[column dir nulls])
109
+ return if none?(hash)
110
+
111
+ col = sort_column(get(hash, "column"), "#{path}.column")
112
+ dir = pick(get(hash, "dir"), %w[asc desc])
113
+ err("#{path}.dir", "invalid", 'must be "asc" or "desc"') unless dir
114
+ nulls = sort_nulls(hash, path)
115
+ Sort.new(column: col.name, dir: dir, nulls: nulls) unless none?(col) || dir.nil?
116
+ end
117
+
118
+ def sort_column(input, path)
119
+ col = column(input, path)
120
+ err(path, "not_sortable", %(cannot sort by "#{col.name}")) unless none?(col) || col.sort
121
+ col
122
+ end
123
+
124
+ def sort_nulls(hash, path)
125
+ nulls = pick(get(hash, "nulls"), %w[first last])
126
+ err("#{path}.nulls", "invalid", 'must be "first" or "last"') if hash.key?("nulls") && !nulls
127
+ nulls
128
+ end
129
+ end
130
+ end
131
+ end
@@ -0,0 +1,68 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lattice
4
+ module Grid
5
+ # The rules for tree data: the path of row keys to the parent row. Not with group, pivot or aggregate.
6
+ class Parser
7
+ private
8
+
9
+ # The tree of the request, or nil. `parts` and `optional` are the other parts of the request.
10
+ def tree_part(hash, parts, optional)
11
+ return unless hash.key?("tree")
12
+
13
+ tree = tree(hash["tree"], parts[:group], parts[:aggregate], optional[:pivot])
14
+ none?(tree) ? nil : tree
15
+ end
16
+
17
+ def tree(input, group, aggregate, pivot)
18
+ hash = obj(input, "tree", %w[keys])
19
+ return NONE if none?(hash)
20
+
21
+ column = tree_column
22
+ return NONE if none?(column)
23
+ if flat?(group, aggregate, pivot)
24
+ return err("tree", "invalid", "tree data cannot have group, pivot or aggregate")
25
+ end
26
+
27
+ tree_keys(get(hash, "keys"), @columns.values.find(&:key).type, column.path)
28
+ end
29
+
30
+ # The parent or path column, when the allow-list also has a key column.
31
+ def tree_column
32
+ column = @columns.values.find { |c| c.parent || c.path }
33
+ return column if column && @key
34
+
35
+ err("tree", "invalid", "tree data needs a key column and a parent or path column")
36
+ end
37
+
38
+ # True when the request has a group, a pivot or an aggregate.
39
+ def flat?(group, aggregate, pivot)
40
+ (!none?(group) && group.by.any?) || !pivot.nil? || (!none?(aggregate) && aggregate.any?)
41
+ end
42
+
43
+ def tree_keys(input, type, path_mode)
44
+ if Kind.of?(input, Array) && input.size > LIMITS[:maxTreeDepth]
45
+ return err("tree.keys", "too_deep", "tree depth is at most #{LIMITS[:maxTreeDepth]}")
46
+ end
47
+
48
+ items = list(input, "tree.keys", LIMITS[:maxTreeDepth])
49
+ return NONE if none?(items)
50
+
51
+ out = items.each_with_index.map { |k, i| tree_key(k, type, path_mode, "tree.keys[#{i}]") }
52
+ none?(*out) ? NONE : Tree.new(keys: out.freeze)
53
+ end
54
+
55
+ # A number key is an integer, so each port writes it in a path the same way.
56
+ def tree_key(input, type, path_mode, path)
57
+ value = scalar(input, type, path)
58
+ return value if none?(value)
59
+ return Kind.safe_int(value) || err(path, "invalid", "must be an integer") if Kind.of?(value, Numeric)
60
+ if path_mode && Kind.string?(value) && value.include?(TREE_PATH_SEPARATOR)
61
+ return err(path, "invalid", %(must not contain "#{TREE_PATH_SEPARATOR}"))
62
+ end
63
+
64
+ value
65
+ end
66
+ end
67
+ end
68
+ end
@@ -0,0 +1,126 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lattice
4
+ module Grid
5
+ # A port of `parseRowsRequest` in packages/protocol/src/parse.ts. It never raises. NONE is the
6
+ # TypeScript `undefined`. The rules are in parser/*.rb.
7
+ class Parser
8
+ NONE = Object.new.freeze
9
+ BAD_STRING = "must not contain U+0000 or a lone surrogate"
10
+
11
+ attr_reader :issues
12
+
13
+ def initialize(columns)
14
+ @columns = columns.to_h { |c| [c.name, c] }
15
+ @key = columns.any?(&:key)
16
+ @issues = []
17
+ @nodes = 0
18
+ @values = 0
19
+ @stopped = false
20
+ end
21
+
22
+ private
23
+
24
+ def err(path, code, message)
25
+ @issues << Issue.new(path: path, code: code, message: message) if @issues.size < LIMITS[:maxErrors]
26
+ NONE
27
+ end
28
+
29
+ # Postgres cannot store U+0000 in text, and Ruby and Python reject a lone surrogate.
30
+ def nul(path)
31
+ err(path, "bad_string", BAD_STRING)
32
+ end
33
+
34
+ def none?(*values)
35
+ values.any? { |v| NONE.equal?(v) }
36
+ end
37
+
38
+ # A copy of a Hash with String keys, or nil. A key that is not a String or a Symbol becomes "?".
39
+ def rec(input)
40
+ return unless Kind.of?(input, Hash)
41
+
42
+ input.each_pair.to_h { |k, v| [key_name(k), v] }
43
+ end
44
+
45
+ def key_name(key)
46
+ name = Kind.of?(key, Symbol) ? key.to_s : key
47
+ Kind.string?(name) ? name.scrub : "?"
48
+ end
49
+
50
+ def get(hash, key)
51
+ hash.fetch(key, NONE)
52
+ end
53
+
54
+ # A Hash with only the given keys, or NONE.
55
+ def obj(input, path, keys)
56
+ hash = rec(input)
57
+ return err(path, "invalid", "must be an object") unless hash
58
+
59
+ (hash.keys - keys).each do |k|
60
+ err(path.empty? ? k : "#{path}.#{k}", "unknown_key", %(unknown key "#{k}"))
61
+ end
62
+ hash
63
+ end
64
+
65
+ def list(input, path, max, min = 0)
66
+ return err(path, "invalid", "must be an array") unless Kind.of?(input, Array)
67
+ return err(path, "too_long", "at most #{max} items") if input.size > max
68
+ return err(path, "invalid", "at least #{min} items") if input.size < min
69
+
70
+ input
71
+ end
72
+
73
+ def str(input, path, max)
74
+ return err(path, "invalid", "must be a string") unless Kind.string?(input)
75
+
76
+ checked_string(input, path, max)
77
+ end
78
+
79
+ # The length check, then the bad string check, as in the TypeScript parser.
80
+ def checked_string(input, path, max)
81
+ return err(path, "too_long", "at most #{max} characters") if Kind.js_length(input) > max
82
+ return nul(path) if Kind.bad_string?(input)
83
+
84
+ String.new(input).freeze
85
+ end
86
+
87
+ # The element of `allowed` that equals `value`, or nil.
88
+ def pick(value, allowed)
89
+ allowed.find { |a| a == value } if Kind.string?(value)
90
+ end
91
+
92
+ def column(input, path)
93
+ name = str(input, path, LIMITS[:maxString])
94
+ return NONE if none?(name)
95
+
96
+ @columns.fetch(name) { err(path, "unknown_column", %(unknown column "#{name}")) }
97
+ end
98
+
99
+ # A value of the column type. nil only when `nullable`.
100
+ def scalar(input, type, path, nullable: false)
101
+ return nil if nullable && input.nil?
102
+
103
+ value = typed(input, type)
104
+ return err(path, "invalid", "must be a #{type}") if value.nil?
105
+ return checked_string(value, path, LIMITS[:maxString]) if Kind.string?(value)
106
+
107
+ value
108
+ end
109
+
110
+ # The value when it has the column type, else nil.
111
+ def typed(input, type)
112
+ case type
113
+ when "string" then input if Kind.string?(input)
114
+ when "number" then Kind.number(input)
115
+ when "boolean" then input if Kind.boolean?(input)
116
+ else input if Dates.valid?(input)
117
+ end
118
+ end
119
+ end
120
+ end
121
+ end
122
+
123
+ require_relative "parser/request_rules"
124
+ require_relative "parser/filter_rules"
125
+ require_relative "parser/group_rules"
126
+ require_relative "parser/tree_rules"
@@ -0,0 +1,78 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lattice
4
+ module Grid
5
+ # The pivot: its keys in the scope, its columns, and one aggregate cell for each key and value.
6
+ class PivotSql
7
+ def initialize(context)
8
+ @context = context
9
+ @sql = context.sql
10
+ @pivot = context.request.pivot
11
+ end
12
+
13
+ def by
14
+ @pivot ? @pivot.by : []
15
+ end
16
+
17
+ def values
18
+ @pivot ? @pivot.values : []
19
+ end
20
+
21
+ # Every pivot key in the scope, sorted ascending with nulls last. Above LIMITS[:maxPivotValues] it
22
+ # raises `pivot_too_wide`, before any pivot SQL is built.
23
+ def combos
24
+ return [] unless @pivot
25
+
26
+ @combos ||= read_combos
27
+ end
28
+
29
+ def selects(aggregates)
30
+ combos.each_with_index.flat_map do |combo, c|
31
+ cond = match(combo)
32
+ values.each_with_index.map { |agg, j| aggregates.node(agg, j, "v", cond).as("p#{c}_#{j}") }
33
+ end
34
+ end
35
+
36
+ def cells(row)
37
+ combos.each_with_index.with_object({}) do |(combo, c), out|
38
+ values.each_with_index { |agg, j| out[field(combo, agg)] = @context.cells.aggregate(agg, row["p#{c}_#{j}"]) }
39
+ end
40
+ end
41
+
42
+ def columns
43
+ combos.flat_map { |combo| values.map { |agg| { field: field(combo, agg), keys: combo, value: agg.key } } }
44
+ end
45
+
46
+ private
47
+
48
+ def read_combos
49
+ rows = @context.select_all(combos_relation.limit(LIMITS[:maxPivotValues] + 1))
50
+ too_wide if rows.size > LIMITS[:maxPivotValues]
51
+
52
+ rows.map { |row| by.each_with_index.map { |n, i| @context.cells.cell(n, row["k#{i}"]) } }
53
+ end
54
+
55
+ def combos_relation
56
+ columns = by.map { |n| @sql.table[n] }
57
+ @context.base.select(*columns.each_with_index.map { |c, i| c.as("k#{i}") })
58
+ .group(*columns).reorder(*by.map { |n| @sql.order(n, "asc", "last") })
59
+ end
60
+
61
+ def too_wide
62
+ count = @context.model.unscoped.from(combos_relation.unscope(:order), "lattice_pivot").count
63
+ message = "#{count} distinct pivot values; at most #{LIMITS[:maxPivotValues]}"
64
+ raise Failure, Issue.new(path: "pivot", code: "pivot_too_wide", message: message)
65
+ end
66
+
67
+ def match(combo)
68
+ parts = by.each_with_index.map { |n, i| @sql.equal(n, combo[i], AggregateSql::ROWS) }
69
+ Arel::Nodes::Grouping.new(Arel::Nodes::And.new(parts))
70
+ end
71
+
72
+ # The compact JSON array of the keys and the value key, as JavaScript writes it.
73
+ def field(combo, agg)
74
+ Json.generate(combo + [agg.key])
75
+ end
76
+ end
77
+ end
78
+ end
@@ -0,0 +1,76 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lattice
4
+ module Grid
5
+ # Answers a RowsRequest from an ActiveRecord relation, with the semantics of the reference evaluator
6
+ # (packages/protocol/src/evaluate.ts). The relation is the scope: keep tenant conditions in it.
7
+ #
8
+ # Lattice::Grid::Query.new(Person.where(account: current_account), columns: COLUMNS, key: "id").call(params)
9
+ #
10
+ # `call` returns a RowsResponse Hash, or `{ errors: [...] }` when the request is bad.
11
+ class Query
12
+ def initialize(scope, columns:, key: nil)
13
+ @scope = scope
14
+ @columns = columns.first.is_a?(Column) ? columns : Column.list(columns, key: key)
15
+ end
16
+
17
+ # `input` is a parsed JSON request (a Hash), or a Request.
18
+ def call(input)
19
+ request = parse(input)
20
+ return request unless Kind.of?(request, Request)
21
+
22
+ Run.new(Context.new(@scope, @columns, request)).response
23
+ rescue Failure => e
24
+ self.class.errors([e.issue])
25
+ end
26
+
27
+ def self.errors(issues)
28
+ { errors: issues.map(&:to_h) }
29
+ end
30
+
31
+ private
32
+
33
+ def parse(input)
34
+ return input if Kind.of?(input, Request)
35
+
36
+ result = Request.parse(input, columns: @columns)
37
+ result.ok? ? result.value : self.class.errors(result.errors)
38
+ end
39
+ end
40
+
41
+ # The work for one request: the level rows, then the response fields.
42
+ class Run
43
+ def initialize(context)
44
+ @context = context
45
+ @request = context.request
46
+ @pivot = PivotSql.new(context)
47
+ @aggregates = AggregateSql.new(context, @pivot)
48
+ end
49
+
50
+ def response
51
+ @pivot.combos
52
+ page = level.page
53
+ out = { rows: page.rows }
54
+ out[:cursor] = page.cursor if page.cursor
55
+ out[:count] = page.known || level.count if @request.count || page.last
56
+ out.merge(extras)
57
+ end
58
+
59
+ private
60
+
61
+ def level
62
+ @level ||= if @context.group_level? then GroupLevel.new(@context, @aggregates)
63
+ elsif @request.pivot then PivotRow.new(@context, @aggregates)
64
+ else LeafLevel.new(@context)
65
+ end
66
+ end
67
+
68
+ def extras
69
+ out = {}
70
+ out[:pivotColumns] = @pivot.columns if @request.pivot
71
+ out[:total] = @aggregates.total if @request.aggregate.any?
72
+ out
73
+ end
74
+ end
75
+ end
76
+ end
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lattice
4
+ module Grid
5
+ # A RowsRequest that passed the allow-list. Every part is a frozen value object.
6
+ Request = Data.define(:v, :range, :sort, :filter, :search, :group, :aggregate, :pivot, :columns, :count, :tree) do
7
+ include Wire
8
+
9
+ # Checks a request (parsed JSON) against the allow-list. This is the trust boundary.
10
+ # It never raises. It returns a Result with the request, or with the errors.
11
+ def self.parse(input, columns:, key: nil)
12
+ parser = Parser.new(columns.first.is_a?(Column) ? columns : Column.list(columns, key: key))
13
+ value = parser.request(input)
14
+ errors = parser.issues.freeze
15
+ Result.new(value: errors.empty? ? value : nil, errors: errors)
16
+ end
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,60 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Lattice
6
+ # The response helper and the Rails controller concern.
7
+ module Grid
8
+ ROUTING_KEYS = %w[controller action format].freeze
9
+
10
+ module_function
11
+
12
+ # The response for one request, for `render json:`. `params` is a JSON body (a String), a Hash,
13
+ # or Rails params. Prefer the raw body: Rails params can add keys and can change `null` in arrays.
14
+ # The response has `errors` when the request is bad; send it with status 400.
15
+ def respond(scope, params, columns:, key: nil, max_body: 1_000_000)
16
+ input = request_input(params, max_body)
17
+ return input if input.is_a?(Hash) && input.key?(:errors)
18
+
19
+ Query.new(scope, columns: columns, key: key).call(input)
20
+ end
21
+
22
+ def request_input(params, max_body)
23
+ case params
24
+ when String then json(params, max_body)
25
+ when Hash then params
26
+ else params.respond_to?(:to_unsafe_h) ? params.to_unsafe_h.except(*ROUTING_KEYS) : params
27
+ end
28
+ end
29
+
30
+ def json(body, max_body)
31
+ return error("too_long", "at most #{max_body} bytes") if body.bytesize > max_body
32
+
33
+ text = body.dup.force_encoding(Encoding::UTF_8)
34
+ return error("invalid", "must be JSON") unless text.valid_encoding?
35
+
36
+ Json.parse(text)
37
+ rescue JSON::NestingError
38
+ error("too_deep", "JSON nesting is too deep")
39
+ rescue JSON::ParserError, EncodingError
40
+ error("invalid", "must be JSON")
41
+ end
42
+
43
+ def error(code, message)
44
+ Query.errors([Issue.new(path: "", code: code, message: message)])
45
+ end
46
+
47
+ # Include in a Rails controller:
48
+ #
49
+ # def rows
50
+ # render_lattice(Person.where(account: current_account), columns: COLUMNS, key: "id")
51
+ # end
52
+ module Controller
53
+ # Reads the raw JSON body, and renders the response, or the errors with status 400.
54
+ def render_lattice(scope, columns:, key: nil, max_body: 1_000_000)
55
+ body = Grid.respond(scope, request.raw_post, columns: columns, key: key, max_body: max_body)
56
+ render json: body, status: body.key?(:errors) ? :bad_request : :ok
57
+ end
58
+ end
59
+ end
60
+ end
@@ -0,0 +1,103 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lattice
4
+ module Grid
5
+ # Arel nodes for one model. Column names come only from the allow-list. Every value is a bind parameter.
6
+ class Sql
7
+ NEVER = Arel::Nodes::Grouping.new(Arel.sql("1 = 0"))
8
+ STRING = ActiveModel::Type::String.new
9
+ VALUE = ActiveModel::Type::Value.new
10
+ BOOLEAN = ActiveModel::Type::Boolean.new
11
+ # Binary collations: strings sort in code point order, as the protocol needs.
12
+ COLLATIONS = { "postg" => '"C"', "mysql" => "utf8mb4_bin", "trilogy" => "utf8mb4_bin" }.freeze
13
+
14
+ attr_reader :table
15
+
16
+ def initialize(model, columns)
17
+ @table = model.arel_table
18
+ @types = columns.to_h { |c| [c.name, c.type] }
19
+ @adapter = model.connection_db_config.adapter.to_s
20
+ end
21
+
22
+ def postgres?
23
+ @adapter.include?("postg")
24
+ end
25
+
26
+ def sqlite?
27
+ @adapter.include?("sqlite")
28
+ end
29
+
30
+ # The node as a string. MySQL casts to CHAR, not to TEXT.
31
+ def text(node)
32
+ cast(node, @adapter.match?(/mysql|trilogy/) ? "CHAR" : "TEXT")
33
+ end
34
+
35
+ def type(name)
36
+ @types.fetch(name)
37
+ end
38
+
39
+ def bind(value, type = VALUE)
40
+ Arel::Nodes::BindParam.new(ActiveRecord::Relation::QueryAttribute.new("lattice", value, type))
41
+ end
42
+
43
+ def collated(name, table = @table)
44
+ collation = COLLATIONS.find { |adapter, _| @adapter.include?(adapter) }&.last if type(name) == "string"
45
+ return table[name] unless collation
46
+
47
+ Arel::Nodes::InfixOperation.new("COLLATE", table[name], Arel.sql(collation))
48
+ end
49
+
50
+ # The column as the protocol compares and sorts it. SQLite keeps dates as text, so it compares Julian days.
51
+ def ordered(name, table = @table)
52
+ return function("julianday", table[name]) if type(name) == "date" && sqlite?
53
+
54
+ collated(name, table)
55
+ end
56
+
57
+ # A client value as a bind parameter, in the form that `ordered` compares with.
58
+ def value(name, value)
59
+ case type(name)
60
+ when "string" then bind(value, STRING)
61
+ when "boolean" then bind(value, BOOLEAN)
62
+ when "date" then date(bind(Dates.utc_text(value), STRING))
63
+ else number(value)
64
+ end
65
+ end
66
+
67
+ def equal(name, value, table = @table)
68
+ value.nil? ? table[name].eq(nil) : ordered(name, table).eq(value(name, value))
69
+ end
70
+
71
+ def order(name, dir, nulls, table = @table)
72
+ node = dir == "desc" ? ordered(name, table).desc : ordered(name, table).asc
73
+ nulls == "first" ? node.nulls_first : node.nulls_last
74
+ end
75
+
76
+ def function(name, *args)
77
+ Arel::Nodes::NamedFunction.new(name, args)
78
+ end
79
+
80
+ private
81
+
82
+ def date(node)
83
+ return function("julianday", node) if sqlite?
84
+ return cast(node, "TIMESTAMP") if postgres?
85
+
86
+ node
87
+ end
88
+
89
+ # Postgres types an untyped parameter from the column, so a fraction or a big integer needs a cast.
90
+ def number(value)
91
+ node = bind(value)
92
+ return node unless postgres?
93
+ return node if value.is_a?(Integer) && value.abs < 2**31
94
+
95
+ cast(node, value.is_a?(Integer) ? "BIGINT" : "DOUBLE PRECISION")
96
+ end
97
+
98
+ def cast(node, type)
99
+ function("CAST", Arel::Nodes::As.new(node, Arel.sql(type)))
100
+ end
101
+ end
102
+ end
103
+ end