elasticsearch_record 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (57) hide show
  1. checksums.yaml +7 -0
  2. data/.rspec +3 -0
  3. data/.ruby-version +1 -0
  4. data/Gemfile +6 -0
  5. data/Gemfile.lock +74 -0
  6. data/README.md +216 -0
  7. data/Rakefile +8 -0
  8. data/docs/CHANGELOG.md +44 -0
  9. data/docs/CODE_OF_CONDUCT.md +84 -0
  10. data/docs/LICENSE.txt +21 -0
  11. data/lib/active_record/connection_adapters/elasticsearch/column.rb +32 -0
  12. data/lib/active_record/connection_adapters/elasticsearch/database_statements.rb +149 -0
  13. data/lib/active_record/connection_adapters/elasticsearch/quoting.rb +38 -0
  14. data/lib/active_record/connection_adapters/elasticsearch/schema_statements.rb +134 -0
  15. data/lib/active_record/connection_adapters/elasticsearch/type/format_string.rb +28 -0
  16. data/lib/active_record/connection_adapters/elasticsearch/type/multicast_value.rb +52 -0
  17. data/lib/active_record/connection_adapters/elasticsearch/type/object.rb +44 -0
  18. data/lib/active_record/connection_adapters/elasticsearch/type/range.rb +42 -0
  19. data/lib/active_record/connection_adapters/elasticsearch/type.rb +16 -0
  20. data/lib/active_record/connection_adapters/elasticsearch_adapter.rb +197 -0
  21. data/lib/arel/collectors/elasticsearch_query.rb +112 -0
  22. data/lib/arel/nodes/select_agg.rb +22 -0
  23. data/lib/arel/nodes/select_configure.rb +9 -0
  24. data/lib/arel/nodes/select_kind.rb +9 -0
  25. data/lib/arel/nodes/select_query.rb +20 -0
  26. data/lib/arel/visitors/elasticsearch.rb +589 -0
  27. data/lib/elasticsearch_record/base.rb +14 -0
  28. data/lib/elasticsearch_record/core.rb +59 -0
  29. data/lib/elasticsearch_record/extensions/relation.rb +15 -0
  30. data/lib/elasticsearch_record/gem_version.rb +17 -0
  31. data/lib/elasticsearch_record/instrumentation/controller_runtime.rb +39 -0
  32. data/lib/elasticsearch_record/instrumentation/log_subscriber.rb +70 -0
  33. data/lib/elasticsearch_record/instrumentation/railtie.rb +16 -0
  34. data/lib/elasticsearch_record/instrumentation.rb +17 -0
  35. data/lib/elasticsearch_record/model_schema.rb +43 -0
  36. data/lib/elasticsearch_record/patches/active_record/relation_merger_patch.rb +85 -0
  37. data/lib/elasticsearch_record/patches/arel/select_core_patch.rb +64 -0
  38. data/lib/elasticsearch_record/patches/arel/select_manager_patch.rb +91 -0
  39. data/lib/elasticsearch_record/patches/arel/select_statement_patch.rb +41 -0
  40. data/lib/elasticsearch_record/patches/arel/update_manager_patch.rb +46 -0
  41. data/lib/elasticsearch_record/patches/arel/update_statement_patch.rb +60 -0
  42. data/lib/elasticsearch_record/persistence.rb +80 -0
  43. data/lib/elasticsearch_record/query.rb +129 -0
  44. data/lib/elasticsearch_record/querying.rb +90 -0
  45. data/lib/elasticsearch_record/relation/calculation_methods.rb +155 -0
  46. data/lib/elasticsearch_record/relation/core_methods.rb +64 -0
  47. data/lib/elasticsearch_record/relation/query_clause.rb +43 -0
  48. data/lib/elasticsearch_record/relation/query_clause_tree.rb +94 -0
  49. data/lib/elasticsearch_record/relation/query_methods.rb +276 -0
  50. data/lib/elasticsearch_record/relation/result_methods.rb +222 -0
  51. data/lib/elasticsearch_record/relation/value_methods.rb +54 -0
  52. data/lib/elasticsearch_record/result.rb +236 -0
  53. data/lib/elasticsearch_record/statement_cache.rb +87 -0
  54. data/lib/elasticsearch_record/version.rb +10 -0
  55. data/lib/elasticsearch_record.rb +60 -0
  56. data/sig/elasticsearch_record.rbs +4 -0
  57. metadata +175 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 9bd7858c5e59826439234e17437d5b8ff62eebbced936a5effee9da19159de5e
4
+ data.tar.gz: ae5d249a7d888363381bee306184c40979445aea26c5e1eec98ac94e11009e88
5
+ SHA512:
6
+ metadata.gz: 23d1062c88940694455c0ef93b7fa7f9c648b20011ed69125234304b9e5e1f61a3ccffa87967af8b757fac7e9846c66051b3517b210d3a91f3e41d71ccd7c057
7
+ data.tar.gz: c975c08bfe47faa8b098f7a457ceb828a8314e3a51c0e0554caa6f73d08b85ce168b4ca3466a54f392336debdae5c44ddebe267c83bda1eb2ee94c9f2b059362
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.ruby-version ADDED
@@ -0,0 +1 @@
1
+ 3.1.2
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in elasticsearch_record.gemspec
6
+ gemspec
data/Gemfile.lock ADDED
@@ -0,0 +1,74 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ elasticsearch_record (0.1.0)
5
+ activerecord (~> 7.0.0)
6
+ elasticsearch (~> 8.4)
7
+
8
+ GEM
9
+ remote: https://rubygems.org/
10
+ specs:
11
+ activemodel (7.0.4)
12
+ activesupport (= 7.0.4)
13
+ activerecord (7.0.4)
14
+ activemodel (= 7.0.4)
15
+ activesupport (= 7.0.4)
16
+ activesupport (7.0.4)
17
+ concurrent-ruby (~> 1.0, >= 1.0.2)
18
+ i18n (>= 1.6, < 2)
19
+ minitest (>= 5.1)
20
+ tzinfo (~> 2.0)
21
+ concurrent-ruby (1.1.10)
22
+ diff-lcs (1.5.0)
23
+ docile (1.4.0)
24
+ elastic-transport (8.1.0)
25
+ faraday (< 3)
26
+ multi_json
27
+ elasticsearch (8.4.0)
28
+ elastic-transport (~> 8)
29
+ elasticsearch-api (= 8.4.0)
30
+ elasticsearch-api (8.4.0)
31
+ multi_json
32
+ faraday (2.5.2)
33
+ faraday-net_http (>= 2.0, < 3.1)
34
+ ruby2_keywords (>= 0.0.4)
35
+ faraday-net_http (3.0.0)
36
+ i18n (1.12.0)
37
+ concurrent-ruby (~> 1.0)
38
+ minitest (5.16.3)
39
+ multi_json (1.15.0)
40
+ rake (13.0.6)
41
+ rspec (3.11.0)
42
+ rspec-core (~> 3.11.0)
43
+ rspec-expectations (~> 3.11.0)
44
+ rspec-mocks (~> 3.11.0)
45
+ rspec-core (3.11.0)
46
+ rspec-support (~> 3.11.0)
47
+ rspec-expectations (3.11.1)
48
+ diff-lcs (>= 1.2.0, < 2.0)
49
+ rspec-support (~> 3.11.0)
50
+ rspec-mocks (3.11.1)
51
+ diff-lcs (>= 1.2.0, < 2.0)
52
+ rspec-support (~> 3.11.0)
53
+ rspec-support (3.11.1)
54
+ ruby2_keywords (0.0.5)
55
+ simplecov (0.21.2)
56
+ docile (~> 1.1)
57
+ simplecov-html (~> 0.11)
58
+ simplecov_json_formatter (~> 0.1)
59
+ simplecov-html (0.12.3)
60
+ simplecov_json_formatter (0.1.4)
61
+ tzinfo (2.0.5)
62
+ concurrent-ruby (~> 1.0)
63
+
64
+ PLATFORMS
65
+ x86_64-linux
66
+
67
+ DEPENDENCIES
68
+ elasticsearch_record!
69
+ rake (~> 13.0)
70
+ rspec (~> 3.0)
71
+ simplecov (~> 0.21)
72
+
73
+ BUNDLED WITH
74
+ 2.3.18
data/README.md ADDED
@@ -0,0 +1,216 @@
1
+ # ElasticsearchRecord
2
+
3
+ ActiveRecord functionality for Elasticsearch indexes & documents.
4
+
5
+ _ElasticsearchRecord is a ActiveRecord-fork and tries to provide the same functionality for Elasticsearch._
6
+
7
+ -----
8
+
9
+ **PLEASE NOTE:**
10
+ - This is still in **development**!
11
+ - Specs & documentation will follow.
12
+ - You might experience BUGs and Exceptions...
13
+ - Currently supports only ActiveRecord 7.0 + Elasticsearch 8.4 _(downgrade for rails 6.x is planned in future versions)_
14
+
15
+ -----
16
+
17
+ ## Installation
18
+
19
+ Add this line to your application's Gemfile:
20
+
21
+ ```ruby
22
+ gem 'elasticsearch_record'
23
+ ```
24
+
25
+ And then execute:
26
+
27
+ $ bundle install
28
+
29
+ Or install it yourself as:
30
+
31
+ $ gem install elasticsearch_record
32
+
33
+
34
+ ## Features
35
+ * CRUD: Reading and Writing Data as already used for ActiveRecord models ```create, update, delete```
36
+ * Query-chaining through the Active Record Query Interface
37
+ * Query interface with additional methods for ```filter, must, must_not, should```
38
+ * Aggregation queries ```aggregate```
39
+ * Instrumentation for ElasticsearchRecord
40
+
41
+ ## Contra - what it _(currently)_ can not
42
+ * Query-based associations like 'has_one' through a single _(or multiple)_ queries - aka. joins
43
+ * complex, combined or nested queries ```and, or, Model.arel ...```
44
+ * Create mappings / schema through migrations _(so no create_table, update_column, ...)_
45
+ * Schema dumps
46
+ * Manage indexes and mappings
47
+
48
+
49
+ ## Setup
50
+
51
+ ### a) Update your **database.yml** and add a elasticsearch connection:
52
+ ```yml
53
+ # config/database.yml
54
+
55
+ development:
56
+ primary:
57
+ # <...>
58
+
59
+ # elasticsearch
60
+ elasticsearch:
61
+ adapter: elasticsearch
62
+ host: localhost:9200
63
+ user: elastic
64
+ password: '****'
65
+ log: true
66
+
67
+ production:
68
+ ...
69
+
70
+ test:
71
+ ...
72
+
73
+
74
+ ```
75
+
76
+ ### b) Require ```elasticsearch_record/instrumentation``` in your application.rb (if you want to...):
77
+ ```ruby
78
+ # config/application.rb
79
+ require_relative "boot"
80
+
81
+ require "rails"
82
+ # Pick the frameworks you want:
83
+
84
+ # ...
85
+ require 'elasticsearch_record/instrumentation'
86
+
87
+ module Application
88
+ # ...
89
+ end
90
+ ```
91
+
92
+ ### c) Create a model that inherits from ```ElasticsearchRecord::Base``` model.
93
+ ```ruby
94
+ # app/models/application_elasticsearch_record.rb
95
+
96
+ class Search < ElasticsearchRecord::Base
97
+
98
+ end
99
+
100
+ ```
101
+
102
+ ### d) have FUN with your model:
103
+ ```ruby
104
+ scope = Search.filter(term: {name: 'MyImportantObject'}).limit(5)
105
+ obj = scope.take
106
+
107
+ obj.update(name: "Not-So-Important")
108
+
109
+ scope.where(kind: :undefined).offset(10).update_all(name: "New Name")
110
+
111
+ ```
112
+
113
+ ## Active Record Query Interface
114
+
115
+ ### Refactored ```where``` method:
116
+
117
+ Different to the default where-method you can now use it in different ways.
118
+
119
+ Using it by default with a Hash, the method decides itself to either add a filter, or must_not query.
120
+
121
+ _Hint: If not overwritten through ```kind(...)``` a default kind **:bool** will be used._
122
+ ```ruby
123
+ # use it by default
124
+ Search.where(name: 'A nice object')
125
+ # > filter: {term: {name: 'A nice object'}}
126
+
127
+ # use it by default with an array
128
+ Search.where(name: ['A nice object','or other object'])
129
+ # > filter: {terms: {name: ['A nice object','or other object']}}
130
+
131
+ # use it by default with nil
132
+ Search.where(name: nil)
133
+ # > must_not: { exists: { field: 'name' } }
134
+
135
+ # -------------------------------------------------------------------
136
+
137
+ # use it with a prefix
138
+ Search.where(:should, term: {name: 'Mano'})
139
+ # > should: {term: {name: 'Mano'}}
140
+ ```
141
+
142
+ ### Usage Examples
143
+ ```ruby
144
+ # save a new record
145
+ model = Search.new(name: "Cool object", kind: "open")
146
+ model.save
147
+
148
+ # find a record by id
149
+ MyEsIndex.find_by_id("xyzAbc34")
150
+ ```
151
+
152
+ ### Useful chain methods
153
+ - kind
154
+ - configure
155
+ - aggregate
156
+ - query
157
+ - filter
158
+ - must_not
159
+ - must
160
+ - should
161
+ - aggregate
162
+
163
+ ### Useful calculation methods
164
+ - percentiles
165
+ - percentile_ranks
166
+ - cardinality
167
+ - average
168
+ - minimum
169
+ - maximum
170
+ - sum
171
+ - calculate
172
+
173
+ ### Useful result methods
174
+ - aggregations
175
+ - hits
176
+ - results
177
+ - total
178
+ - msearch
179
+ - agg_pluck
180
+ - composite
181
+ - point_in_time
182
+ - pit_results
183
+
184
+ ### Additional methods
185
+ - to_query
186
+
187
+ -----
188
+
189
+ ### Useful model-class attributes
190
+ - index_base_name
191
+
192
+ ### Useful model methods
193
+ - source_column_names
194
+ - searchable_column_names
195
+ - find_by_query
196
+ - msearch
197
+
198
+
199
+ ## Docs
200
+
201
+ [CHANGELOG](./docs/CHANGELOG.md)
202
+
203
+ ## Contributing
204
+
205
+ Bug reports and pull requests are welcome on GitHub at [elasticsearch_record](https://github.com/ruby-smart/elasticsearch_record).
206
+ This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](./docs/CODE_OF_CONDUCT.md).
207
+
208
+ ## License
209
+
210
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
211
+
212
+ A copy of the [LICENSE](./docs/LICENSE.txt) can be found @ the docs.
213
+
214
+ ## Code of Conduct
215
+
216
+ Everyone interacting in the project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [CODE OF CONDUCT](./docs/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ task default: :spec
data/docs/CHANGELOG.md ADDED
@@ -0,0 +1,44 @@
1
+ # ElasticsearchRecord - CHANGELOG
2
+
3
+ ## [1.0.0] - 2022-10-18
4
+ * [add] patch for ```ActiveRecord::Relation::Merger``` - to support AR-relations
5
+ * [add] ```ElasticsearchRecord::Relation#pit_results``` _offset_ & _yield_ support
6
+ * [add] individual instrumentation names for ```ElasticsearchRecord::Relation``` result methods (like: #aggregations)
7
+ * [rem] cleanup Debugging & logging
8
+ * [fix] quoting for any values
9
+ * [fix] calculation ```count``` method to support already known syntax (with column, distinct, limited, ...)
10
+ * [fix] ```Arel::Nodes``` to support additional args (query, kind, aggs, ...)
11
+ * [fix] _relation manager patch_ to not mash up different relations
12
+ * [fix] ```ElasticsearchRecord``` total calculation for failed queries
13
+ * [fix] ```ElasticsearchRecord::Relation#count``` to correctly _unscope_
14
+ * [fix] ```Arel::Visitors::Elasticsearch```
15
+ * build query where-clauses without existing default query-"kind"
16
+ * directly fail if a grouping _(visit_Arel_Nodes_Grouping)_ was provided
17
+ * forced _failed!_ state was not correctly claimed
18
+ * buggy _assign_-method for nested arrays
19
+ * [fix] ```Arel::Collectors::ElasticsearchQuery```
20
+ * claim for _argument_
21
+ * delete key on _nil_ assign
22
+ * [ref] simplify ```Arel::Collectors::ElasticsearchQuery``` (remove stack & scoping)
23
+ * [ref] simplify ```Arel::Visitors::Elasticsearch``` to support binds (statement cache) and simple where predicates
24
+ * [ref] rename ```ElasticsearchRecord::Query#arguments``` -> _#query_arguments_
25
+
26
+ ## [0.1.2] - 2022-09-23
27
+ * [fix] Records / Elasticsearch index with additional 'id' fields not recognizing
28
+ * [rem] unnecessary & overcomplicated .index_name_delimiter class attribute
29
+
30
+ ## [0.1.1] - 2022-09-22
31
+ * [add] msearch for klass & relation
32
+ * [fix] Gemfile (remove duplicated requirements)
33
+ * [fix] gemspec (dependencies & descriptions)
34
+ * [fix] loading requirements, remove unused code
35
+ * [fix] quoting
36
+ * [fix] arel collector
37
+ * [fix] arel visitor sort & assignment
38
+ * [ref] results builder for multiple responses
39
+ * [ref] log_subscriber to hide index but show 'query time'
40
+ * [ref] model_schema attributes
41
+
42
+ ## [0.1.0] - 2022-09-21
43
+ * Initial commit
44
+ * docs, version, structure
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at tg@reimbursement.institute. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/docs/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2022 Tobias Gonsior
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveRecord
4
+ module ConnectionAdapters
5
+ module Elasticsearch
6
+ class Column < ConnectionAdapters::Column # :nodoc:
7
+
8
+ attr_reader :virtual, :fields
9
+
10
+ def initialize(name, default, sql_type_metadata = nil, null = true, default_function = nil, **kwargs)
11
+ @virtual = kwargs.delete(:virtual)
12
+ @fields = kwargs.delete(:fields)
13
+ super(name, default, sql_type_metadata, null, default_function, **kwargs)
14
+ end
15
+
16
+ # returns true if this column is virtual.
17
+ # Virtual columns cannot be saved.
18
+ # @return [Boolean]
19
+ def virtual?
20
+ !!virtual
21
+ end
22
+
23
+ # returns true if this column has nested fields
24
+ # To receive the nested names just call +#fields+ on this object.
25
+ # @return [Boolean]
26
+ def fields?
27
+ fields.present?
28
+ end
29
+ end
30
+ end
31
+ end
32
+ end
@@ -0,0 +1,149 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveRecord
4
+ module ConnectionAdapters
5
+ module Elasticsearch
6
+ module DatabaseStatements
7
+
8
+ # detects if a query is a write query.
9
+ # since we don't provide a simple string / hash we can now access the query-object and ask for it :)
10
+ # @see ActiveRecord::ConnectionAdapters::DatabaseStatements#write_query?
11
+ # @param [ElasticsearchRecord::Query] query
12
+ # @return [Boolean]
13
+ def write_query?(query)
14
+ query.write?
15
+ end
16
+
17
+ # gets called for all queries
18
+ # @param [ElasticsearchRecord::Query] query
19
+ # @param [String (frozen)] name
20
+ # @param [Array] binds
21
+ # @param [Boolean] prepare - used by the default AbstractAdapter - but not supported and therefore never used!
22
+ # @param [Boolean] async
23
+ # @return [ElasticsearchRecord::Result]
24
+ def exec_query(query, name = "QUERY", binds = [], prepare: false, async: false)
25
+ # validate the query
26
+ raise ActiveRecord::StatementInvalid, 'Unable to execute invalid query' unless query.valid?
27
+
28
+ # checks for write query - raises an exception if connection is locked to readonly ...
29
+ check_if_write_query(query)
30
+
31
+ build_result(
32
+ api(*query.gate, query.query_arguments, name, async: async),
33
+ columns: query.columns
34
+ )
35
+ end
36
+
37
+ # Executes insert +query+ statement in the context of this connection using
38
+ # +binds+ as the bind substitutes. +name+ is logged along with
39
+ # the executed +query+ arguments.
40
+ def exec_insert(query, name = nil, binds = [], _pk = nil, _sequence_name = nil)
41
+ exec_query(query, name, binds)
42
+ end
43
+
44
+ # Executes delete +query+ statement in the context of this connection using
45
+ # +binds+ as the bind substitutes. +name+ is logged along with
46
+ # the executed +query+ arguments.
47
+ # expects a integer as return.
48
+ # @return [Integer]
49
+ def exec_delete(query, name = nil, binds = [])
50
+ exec_query(query, name, binds).total
51
+ end
52
+
53
+ # Executes update +query+ statement in the context of this connection using
54
+ # +binds+ as the bind substitutes. +name+ is logged along with
55
+ # the executed +query+ arguments.
56
+ # expects a integer as return.
57
+ # @return [Integer]
58
+ def exec_update(query, name = nil, binds = [])
59
+ exec_query(query, name, binds).total
60
+ end
61
+
62
+ # executes a msearch for provided arels
63
+ # @return [ElasticsearchRecord::Result]
64
+ def select_multiple(arels, name = "Multi", async: false)
65
+ # transform arels to query objects
66
+ queries = arels.map { |arel| to_sql(arel_from_relation(arel)) }
67
+
68
+ # build new msearch query
69
+ query = ElasticsearchRecord::Query.new(
70
+ index: queries.first&.index,
71
+ type: ElasticsearchRecord::Query::TYPE_MSEARCH,
72
+ body: queries.map { |q| { search: q.body } })
73
+
74
+ exec_query(query, name, async: async)
75
+ end
76
+
77
+ # executes a count query for provided arel
78
+ # @return [Integer]
79
+ def select_count(arel, name = "Count", async: false)
80
+ query = to_sql(arel_from_relation(arel))
81
+
82
+ # build new count query from existing query
83
+ query = ElasticsearchRecord::Query.new(
84
+ index: query.index,
85
+ type: ElasticsearchRecord::Query::TYPE_COUNT,
86
+ body: query.body,
87
+ arguments: query.arguments)
88
+
89
+ exec_query(query, name, async: async).response['count']
90
+ end
91
+
92
+ # # This is used in the StatementCache object. It returns an object that
93
+ # # can be used to query the database repeatedly.
94
+ # # @see ActiveRecord::ConnectionAdapters::DatabaseStatements#cacheable_query
95
+ # def cacheable_query(klass, arel) # :nodoc:
96
+ # # the provided klass is a ActiveRecord::StatementCache and only supports SQL _(String)_ queries.
97
+ # # We force overwrite this class with our own
98
+ #
99
+ #
100
+ # ActiveRecord::StatementCache.partial_query_collector
101
+ #
102
+ # raise "STOP HERE!!!!!!"
103
+ # if prepared_statements
104
+ # sql, binds = visitor.compile(arel.ast, collector)
105
+ # query = klass.query(sql)
106
+ # else
107
+ # collector = klass.partial_query_collector
108
+ # parts, binds = visitor.compile(arel.ast, collector)
109
+ # query = klass.partial_query(parts)
110
+ # end
111
+ # [query, binds]
112
+ # end
113
+
114
+ # calls the +elasticsearch-api+ endpoints by provided namespace and action.
115
+ # if a block was provided it'll yield the response.body and returns the blocks result.
116
+ # otherwise it will return the response itself...
117
+ # @param [Symbol] namespace - the API namespace (e.g. indices, nodes, sql, ...)
118
+ # @param [Symbol] action - the API action to call in tha namespace
119
+ # @param [Hash] arguments - action arguments
120
+ # @param [String (frozen)] name - the logging name
121
+ # @param [Boolean] async - send async (default: false) - currently not supported
122
+ # @return [Elasticsearch::API::Response, Object]
123
+ def api(namespace, action, arguments = {}, name = 'API', async: false)
124
+ raise ::StandardError, 'ASYNC api calls are not supported' if async
125
+
126
+ # resolve the API target
127
+ target = namespace == :core ? @connection : @connection.__send__(namespace)
128
+
129
+ log("#{namespace}.#{action}", arguments, name, async: async) do
130
+ response = ActiveSupport::Dependencies.interlock.permit_concurrent_loads do
131
+ target.__send__(action, arguments)
132
+ end
133
+
134
+ if response.is_a?(::Elasticsearch::API::Response)
135
+ # reverse information for the LogSubscriber - shows the 'query-time' in the logs
136
+ # this works, since we use a referenced hash ...
137
+ arguments[:_qt] = response['took']
138
+
139
+ # raise timeouts
140
+ raise(ActiveRecord::StatementTimeout, "Elasticsearch api request failed due a timeout") if response['timed_out']
141
+ end
142
+
143
+ response
144
+ end
145
+ end
146
+ end
147
+ end
148
+ end
149
+ end