1 | # frozen_string_literal: true |
||
2 | |||
3 | 1 | module NoSE |
|
4 | # Simple DSL for constructing indexes |
||
5 | 1 | class Schema |
|
6 | 1 | attr_reader :model, :indexes |
|
7 | |||
8 | 1 | def initialize(&block) |
|
9 | 8 | @indexes = {} |
|
10 | 8 | instance_eval(&block) if block_given? |
|
11 | end |
||
12 | |||
13 | # Find the schema with the given name |
||
14 | 1 | def self.load(name) |
|
15 | 6 | filename = File.expand_path "../../../schemas/#{name}.rb", __FILE__ |
|
16 | 6 | contents = File.read(filename) |
|
17 | 6 | binding.eval contents, filename |
|
0 ignored issues
–
show
introduced
by
![]() |
|||
18 | end |
||
19 | |||
20 | # rubocop:disable MethodName |
||
0 ignored issues
–
show
|
|||
21 | |||
22 | # Set the model to be used by the schema |
||
23 | # @return [void] |
||
24 | 1 | def Model(name) |
|
25 | 8 | @model = Model.load name |
|
26 | 8 | NoSE::DSL.mixin_fields @model.entities, IndexDSL |
|
27 | end |
||
28 | |||
29 | # Add a simple index for an entity |
||
30 | # @return [void] |
||
31 | 1 | def SimpleIndex(entity) |
|
32 | @indexes[entity] = @model[entity].simple_index |
||
33 | end |
||
34 | |||
35 | # Wrap commands for defining index attributes |
||
36 | # @return [void] |
||
37 | 1 | def Index(key, &block) |
|
38 | # Apply the DSL |
||
39 | 26 | dsl = IndexDSL.new(self) |
|
40 | 26 | dsl.instance_eval(&block) if block_given? |
|
41 | 26 | index = Index.new dsl.hash_fields, dsl.order_fields, dsl.extra, |
|
42 | QueryGraph::Graph.from_path(dsl.path_keys), |
||
43 | saved_key: key |
||
44 | 26 | @indexes[index.key] = index |
|
45 | end |
||
46 | |||
47 | # rubocop:enable MethodName |
||
0 ignored issues
–
show
|
|||
48 | end |
||
49 | |||
50 | # DSL for index creation within a schema |
||
51 | 1 | class IndexDSL |
|
52 | 1 | attr_reader :hash_fields, :order_fields, :extra, :path_keys |
|
53 | |||
54 | 1 | def initialize(schema) |
|
55 | 26 | @schema = schema |
|
56 | 26 | @hash_fields = [] |
|
57 | 26 | @order_fields = [] |
|
58 | 26 | @extra = [] |
|
59 | 26 | @path_keys = [] |
|
60 | end |
||
61 | |||
62 | # rubocop:disable MethodName |
||
0 ignored issues
–
show
|
|||
63 | |||
64 | # Define a list of hash fields |
||
65 | # @return [void] |
||
66 | 1 | def Hash(*fields) |
|
67 | 26 | @hash_fields += fields.flatten |
|
68 | end |
||
69 | |||
70 | # Define a list of ordered fields |
||
71 | # @return [void] |
||
72 | 1 | def Ordered(*fields) |
|
73 | 13 | @order_fields += fields.flatten |
|
74 | end |
||
75 | |||
76 | # Define a list of extra fields |
||
77 | # @return [void] |
||
78 | 1 | def Extra(*fields) |
|
79 | 14 | @extra += fields.flatten |
|
80 | end |
||
81 | |||
82 | # Define the keys for the index path |
||
83 | # @return [void] |
||
84 | 1 | def Path(*keys) |
|
85 | 26 | @path_keys += keys |
|
86 | end |
||
87 | |||
88 | # rubocop:enable MethodName |
||
0 ignored issues
–
show
|
|||
89 | end |
||
90 | end |
||
91 |