post_json 1.0.3
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.
- checksums.yaml +7 -0
- data/MIT-LICENSE +20 -0
- data/README.md +194 -0
- data/Rakefile +21 -0
- data/lib/core_ext/abstract_adapter_extend.rb +16 -0
- data/lib/core_ext/active_record_relation_extend.rb +16 -0
- data/lib/core_ext/hash_extend.rb +36 -0
- data/lib/generators/post_json/install/install_generator.rb +32 -0
- data/lib/generators/post_json/install/templates/create_post_json_documents.rb +13 -0
- data/lib/generators/post_json/install/templates/create_post_json_dynamic_indexes.rb +9 -0
- data/lib/generators/post_json/install/templates/create_post_json_model_settings.rb +18 -0
- data/lib/generators/post_json/install/templates/create_procedures.rb +120 -0
- data/lib/generators/post_json/install/templates/enable_extensions.rb +28 -0
- data/lib/generators/post_json/install/templates/initializer.rb +9 -0
- data/lib/post_json.rb +56 -0
- data/lib/post_json/base.rb +278 -0
- data/lib/post_json/concerns/argument_methods.rb +33 -0
- data/lib/post_json/concerns/dynamic_index_methods.rb +34 -0
- data/lib/post_json/concerns/finder_methods.rb +343 -0
- data/lib/post_json/concerns/query_methods.rb +157 -0
- data/lib/post_json/concerns/settings_methods.rb +106 -0
- data/lib/post_json/dynamic_index.rb +99 -0
- data/lib/post_json/model_settings.rb +17 -0
- data/lib/post_json/query_translator.rb +48 -0
- data/lib/post_json/version.rb +3 -0
- data/spec/dummy/Rakefile +6 -0
- data/spec/dummy/app/assets/javascripts/application.js +13 -0
- data/spec/dummy/app/assets/stylesheets/application.css +13 -0
- data/spec/dummy/app/assets/stylesheets/scaffold.css +56 -0
- data/spec/dummy/app/controllers/application_controller.rb +5 -0
- data/spec/dummy/app/helpers/application_helper.rb +2 -0
- data/spec/dummy/app/views/layouts/application.html.erb +14 -0
- data/spec/dummy/bin/bundle +3 -0
- data/spec/dummy/bin/rails +4 -0
- data/spec/dummy/bin/rake +4 -0
- data/spec/dummy/config.ru +4 -0
- data/spec/dummy/config/application.rb +30 -0
- data/spec/dummy/config/boot.rb +5 -0
- data/spec/dummy/config/database.yml +26 -0
- data/spec/dummy/config/environment.rb +5 -0
- data/spec/dummy/config/environments/development.rb +29 -0
- data/spec/dummy/config/environments/production.rb +80 -0
- data/spec/dummy/config/environments/test.rb +36 -0
- data/spec/dummy/config/initializers/backtrace_silencers.rb +7 -0
- data/spec/dummy/config/initializers/filter_parameter_logging.rb +4 -0
- data/spec/dummy/config/initializers/inflections.rb +16 -0
- data/spec/dummy/config/initializers/mime_types.rb +5 -0
- data/spec/dummy/config/initializers/post_json.rb +5 -0
- data/spec/dummy/config/initializers/secret_token.rb +12 -0
- data/spec/dummy/config/initializers/session_store.rb +3 -0
- data/spec/dummy/config/initializers/wrap_parameters.rb +14 -0
- data/spec/dummy/config/locales/en.yml +23 -0
- data/spec/dummy/config/routes.rb +56 -0
- data/spec/dummy/db/migrate/20131015022029_enable_extensions.rb +28 -0
- data/spec/dummy/db/migrate/20131015022030_create_procedures.rb +120 -0
- data/spec/dummy/db/migrate/20131015022031_create_post_json_model_settings.rb +18 -0
- data/spec/dummy/db/migrate/20131015022032_create_post_json_collections.rb +16 -0
- data/spec/dummy/db/migrate/20131015022033_create_post_json_documents.rb +13 -0
- data/spec/dummy/db/migrate/20131015022034_create_post_json_dynamic_indexes.rb +9 -0
- data/spec/dummy/db/structure.sql +311 -0
- data/spec/dummy/public/404.html +58 -0
- data/spec/dummy/public/422.html +58 -0
- data/spec/dummy/public/500.html +57 -0
- data/spec/dummy/public/favicon.ico +0 -0
- data/spec/models/base_spec.rb +393 -0
- data/spec/models/collection_spec.rb +27 -0
- data/spec/models/queries_spec.rb +164 -0
- data/spec/modules/argument_methods_spec.rb +17 -0
- data/spec/modules/query_methods_spec.rb +69 -0
- data/spec/spec_helper.rb +54 -0
- metadata +184 -0
checksums.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
1
|
+
---
|
2
|
+
SHA1:
|
3
|
+
metadata.gz: 90d8b0c0218c6e80aea604f49fe5ea5dfddff653
|
4
|
+
data.tar.gz: 4e8e16084b21f5909e1d1e2728e5a707483c050b
|
5
|
+
SHA512:
|
6
|
+
metadata.gz: cdb0d422a3cb9ae46eb28d2dc70e9c97ff2513e88654aa729ca207da8f8e835ce546813762446aadf588e298b721b72cb24ee36b69aab0c2ade5dc4b2d3b401e
|
7
|
+
data.tar.gz: a7e994fced38b80d2b2644555bef27d82a62d6a6f00d92719f64f60e19871710ae6e2cbd0456f9d7624de5bd7d924840aa036740f2f1e6b9c38d02ab3ccaf3f7
|
data/MIT-LICENSE
ADDED
@@ -0,0 +1,20 @@
|
|
1
|
+
Copyright 2013 Webnuts (www.webnuts.com / hello@webnuts.com)
|
2
|
+
|
3
|
+
Permission is hereby granted, free of charge, to any person obtaining
|
4
|
+
a copy of this software and associated documentation files (the
|
5
|
+
"Software"), to deal in the Software without restriction, including
|
6
|
+
without limitation the rights to use, copy, modify, merge, publish,
|
7
|
+
distribute, sublicense, and/or sell copies of the Software, and to
|
8
|
+
permit persons to whom the Software is furnished to do so, subject to
|
9
|
+
the following conditions:
|
10
|
+
|
11
|
+
The above copyright notice and this permission notice shall be
|
12
|
+
included in all copies or substantial portions of the Software.
|
13
|
+
|
14
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
15
|
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
16
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
17
|
+
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
18
|
+
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
19
|
+
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
20
|
+
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
data/README.md
ADDED
@@ -0,0 +1,194 @@
|
|
1
|
+
# Welcome to PostJson
|
2
|
+
|
3
|
+
PostJson is everything you expect of ActiveRecord and PostgreSQL, but with the dynamic nature of document databases
|
4
|
+
(free as a bird - no schemas).
|
5
|
+
|
6
|
+
PostJson take full advantage of PostgreSQL 9.2+ support for JavaScript (Google's V8 engine). We started the work on
|
7
|
+
PostJson, because we love document databases and PostgreSQL. PostJson combine features of Ruby, ActiveRecord and
|
8
|
+
PostgreSQL to provide a great document database.
|
9
|
+
|
10
|
+
See example of how we use PostJson as part of Jump...
|
11
|
+
|
12
|
+
|
13
|
+
## Getting started
|
14
|
+
1. Add the gem to your Ruby on Rails application `Gemfile`:
|
15
|
+
|
16
|
+
gem 'post_json'
|
17
|
+
|
18
|
+
2. At the command prompt, install the gem:
|
19
|
+
|
20
|
+
bundle install
|
21
|
+
rails g post_json:install
|
22
|
+
rake db:migrate
|
23
|
+
|
24
|
+
That's it!
|
25
|
+
|
26
|
+
(See POSTGRESQL_INSTALL.md if you need the install instructions for PostgreSQL with PLV8)
|
27
|
+
|
28
|
+
## Using it
|
29
|
+
|
30
|
+
You should feel home right away, if you already know ActiveRecord. PostJson try hard to respect the ActiveRecord
|
31
|
+
API, so methods work and do as you would expect from ActiveRecord.
|
32
|
+
|
33
|
+
PostJson is all about collections. All models represent a collection.
|
34
|
+
|
35
|
+
Also, __notice you don't have to define model attributes anywhere!__
|
36
|
+
|
37
|
+
1. Lets create your first model.
|
38
|
+
|
39
|
+
class Person < PostJson::Collection["people"]
|
40
|
+
end
|
41
|
+
|
42
|
+
me = Person.create(name: "Jacob")
|
43
|
+
|
44
|
+
As you can see it look the same as ActiveRecord, except you define `PostJson::Collection["people"]` instead of
|
45
|
+
`ActiveRecord::Base`.
|
46
|
+
|
47
|
+
`Person` can do the same as any model class inheriting `ActiveRecord::Base`.
|
48
|
+
|
49
|
+
You can also skip the creation of a class:
|
50
|
+
|
51
|
+
people = PostJson::Collection["people"]
|
52
|
+
me = people.create(name: "Jacob")
|
53
|
+
|
54
|
+
2. Adding some validation:
|
55
|
+
|
56
|
+
class Person < PostJson::Collection["people"]
|
57
|
+
validates :name, presence: true
|
58
|
+
end
|
59
|
+
|
60
|
+
PostJson::Collection["people"] returns a class, which is based on `PostJson::Base`, which is based on
|
61
|
+
`ActiveRecord::Base`. So its the exact same validation as you may know.
|
62
|
+
|
63
|
+
Read the <a href="http://guides.rubyonrails.org/active_record_validations.html" target="_blank">Rails guide about validation</a>
|
64
|
+
if you need more information.
|
65
|
+
|
66
|
+
3. Lets create a more complex document and do a query:
|
67
|
+
|
68
|
+
me = Person.create(name: "Jacob", details: {age: 33})
|
69
|
+
|
70
|
+
Now we can make a query and get the document:
|
71
|
+
|
72
|
+
also_me_1 = Person.where(details: {age: 33}).first
|
73
|
+
also_me_2 = Person.where("details.age" => 33).first
|
74
|
+
also_me_3 = Person.where("json_details.age = ?", 33).first
|
75
|
+
|
76
|
+
PostJson support filtering on nested attributes as you can see. The two first queries speak for themself.
|
77
|
+
|
78
|
+
The third (and last) query is special and show it is possible to write real SQL queries. We just need to prefix
|
79
|
+
the JSON attributes with `json_`.
|
80
|
+
|
81
|
+
4. Accessing attributes:
|
82
|
+
|
83
|
+
person = Person.create(name: "Jacob")
|
84
|
+
puts person.name # "Jacob"
|
85
|
+
puts person.name_was # "Jacob"
|
86
|
+
puts person.name_changed? # false
|
87
|
+
puts person.name_change # nil
|
88
|
+
|
89
|
+
person.name = "Martin"
|
90
|
+
|
91
|
+
puts person.name_was # "Jacob"
|
92
|
+
puts person.name # "Martin"
|
93
|
+
puts person.name_changed? # true
|
94
|
+
puts person.name_change # ["Jacob", "Martin"]
|
95
|
+
|
96
|
+
person.save
|
97
|
+
|
98
|
+
puts person.name # "Martin"
|
99
|
+
puts person.name_was # "Martin"
|
100
|
+
puts person.name_changed? # false
|
101
|
+
puts person.name_change # nil
|
102
|
+
|
103
|
+
Like you would expect with ActiveRecord.
|
104
|
+
|
105
|
+
#### All of the following methods are supported
|
106
|
+
|
107
|
+
except
|
108
|
+
limit
|
109
|
+
offset
|
110
|
+
page(page, per_page) # translate to `offset((page-1)*per_page).limit(per_page)`
|
111
|
+
only
|
112
|
+
order
|
113
|
+
reorder
|
114
|
+
reverse_order
|
115
|
+
where
|
116
|
+
|
117
|
+
And ...
|
118
|
+
|
119
|
+
all
|
120
|
+
any?
|
121
|
+
blank?
|
122
|
+
count
|
123
|
+
delete
|
124
|
+
delete_all
|
125
|
+
destroy
|
126
|
+
destroy_all
|
127
|
+
empty?
|
128
|
+
exists?
|
129
|
+
find
|
130
|
+
find_by
|
131
|
+
find_by!
|
132
|
+
find_each
|
133
|
+
find_in_batches
|
134
|
+
first
|
135
|
+
first!
|
136
|
+
first_or_create
|
137
|
+
first_or_initialize
|
138
|
+
ids
|
139
|
+
last
|
140
|
+
load
|
141
|
+
many?
|
142
|
+
pluck
|
143
|
+
select
|
144
|
+
size
|
145
|
+
take
|
146
|
+
take!
|
147
|
+
to_a
|
148
|
+
to_sql
|
149
|
+
|
150
|
+
|
151
|
+
|
152
|
+
|
153
|
+
|
154
|
+
|
155
|
+
|
156
|
+
## Dynamic Indexes
|
157
|
+
|
158
|
+
We have created a feature we call `Dynamic Index`. It will automatically create indexes on slow queries, so queries
|
159
|
+
speed up considerably.
|
160
|
+
|
161
|
+
PostJson will measure the duration of each `SELECT` query and instruct PostgreSQL to create an Expression Index,
|
162
|
+
if the query duration is above a specified threshold.
|
163
|
+
|
164
|
+
Each collection (like PostJson::Collection["people"]) have attribute `use_dynamic_index` (which is true by default) and
|
165
|
+
attribute `create_dynamic_index_milliseconds_threshold` (which is 50 by default).
|
166
|
+
|
167
|
+
Lets say that you execute the following query and the duration is above the threshold of 50 milliseconds:
|
168
|
+
|
169
|
+
`PostJson::Collection["people"].where(name: "Jacob").count`
|
170
|
+
|
171
|
+
PostJson will create (unless it already exists) an Expression Index on `name` behind the scenes. The next time
|
172
|
+
you execute a query with `name` the performance will be much improved.
|
173
|
+
|
174
|
+
## Requirements
|
175
|
+
|
176
|
+
- PostgreSQL 9.2 or 9.3
|
177
|
+
- PostgreSQL PLV8 extension.
|
178
|
+
|
179
|
+
## License
|
180
|
+
|
181
|
+
PostJson is released under the MIT License. See the MIT-LICENSE file.
|
182
|
+
|
183
|
+
## Want to contribute?
|
184
|
+
|
185
|
+
That's awesome, thank you!
|
186
|
+
|
187
|
+
Do you have an idea or suggestion? Please create an issue or send us an e-mail (hello@webnuts.com). We would be happy to implement (if we like the idea) right away.
|
188
|
+
|
189
|
+
You can also send us a pull request with your contribution.
|
190
|
+
|
191
|
+
<a href="http://www.webnuts.com" target="_blank">
|
192
|
+
<img src="http://www.webnuts.com/logo/post_json/logo.png" alt="Webnuts.com">
|
193
|
+
</a>
|
194
|
+
##### Sponsored by Webnuts.com
|
data/Rakefile
ADDED
@@ -0,0 +1,21 @@
|
|
1
|
+
begin
|
2
|
+
require 'bundler/setup'
|
3
|
+
rescue LoadError
|
4
|
+
puts 'You must `gem install bundler` and `bundle install` to run rake tasks'
|
5
|
+
end
|
6
|
+
|
7
|
+
require 'rdoc/task'
|
8
|
+
|
9
|
+
RDoc::Task.new(:rdoc) do |rdoc|
|
10
|
+
rdoc.rdoc_dir = 'rdoc'
|
11
|
+
rdoc.title = 'PostJson'
|
12
|
+
rdoc.options << '--line-numbers'
|
13
|
+
rdoc.rdoc_files.include('README.rdoc')
|
14
|
+
rdoc.rdoc_files.include('lib/**/*.rb')
|
15
|
+
end
|
16
|
+
|
17
|
+
|
18
|
+
|
19
|
+
|
20
|
+
Bundler::GemHelper.install_tasks
|
21
|
+
|
@@ -0,0 +1,16 @@
|
|
1
|
+
ActiveRecord::ConnectionAdapters::AbstractAdapter.class_eval do
|
2
|
+
|
3
|
+
attr_accessor :last_select_query, :last_select_query_duration
|
4
|
+
|
5
|
+
def measure_select_all(arel, name = nil, binds = [])
|
6
|
+
result = nil
|
7
|
+
@last_select_query_duration = Benchmark.realtime do
|
8
|
+
result = original_select_all(arel, name, binds)
|
9
|
+
end
|
10
|
+
@last_select_query = to_sql(arel, binds.dup).strip
|
11
|
+
result
|
12
|
+
end
|
13
|
+
|
14
|
+
alias_method :original_select_all, :select_all
|
15
|
+
alias_method :select_all, :measure_select_all
|
16
|
+
end
|
@@ -0,0 +1,16 @@
|
|
1
|
+
# See https://github.com/rails/rails/blob/master/activerecord/CHANGELOG.md - Fixes #10615
|
2
|
+
#
|
3
|
+
# "Usage of implicit_readonly is being removed. Please usereadonlymethod explicitly to mark records asreadonly"
|
4
|
+
#
|
5
|
+
# The override below can be removed in the future
|
6
|
+
|
7
|
+
ActiveRecord::Relation.class_eval do
|
8
|
+
def exec_queries_without_implicit_readonly
|
9
|
+
records = original_exec_queries
|
10
|
+
records.each { |r| r.instance_variable_set(:@readonly, false) } unless self.readonly_value == true
|
11
|
+
records
|
12
|
+
end
|
13
|
+
|
14
|
+
alias_method :original_exec_queries, :exec_queries
|
15
|
+
alias_method :exec_queries, :exec_queries_without_implicit_readonly
|
16
|
+
end
|
@@ -0,0 +1,36 @@
|
|
1
|
+
class Hash
|
2
|
+
def flatten_hash(prefix = nil)
|
3
|
+
self.inject(HashWithIndifferentAccess.new) do |result, (key, value)|
|
4
|
+
combined_key = [prefix, key].compact.join(".")
|
5
|
+
if value.is_a?(Hash)
|
6
|
+
result.deep_merge!(value.flatten_hash(combined_key))
|
7
|
+
else
|
8
|
+
result[combined_key] = value
|
9
|
+
end
|
10
|
+
result
|
11
|
+
end
|
12
|
+
end
|
13
|
+
|
14
|
+
def deepen_hash
|
15
|
+
self.inject(HashWithIndifferentAccess.new) do |result, (key, value)|
|
16
|
+
path_names = key.split(".")
|
17
|
+
if path_names.length == 1
|
18
|
+
result[key] = value
|
19
|
+
else
|
20
|
+
key_result = path_names.reverse.inject(nil) do |result, path_name|
|
21
|
+
if result == nil
|
22
|
+
HashWithIndifferentAccess.new(path_name => value)
|
23
|
+
else
|
24
|
+
HashWithIndifferentAccess.new(path_name => result)
|
25
|
+
end
|
26
|
+
end
|
27
|
+
result.deep_merge!(key_result)
|
28
|
+
end
|
29
|
+
result
|
30
|
+
end
|
31
|
+
end
|
32
|
+
|
33
|
+
def difference(h2)
|
34
|
+
dup.delete_if { |k, v| h2[k] == v }.merge!(h2.dup.delete_if { |k, v| has_key?(k) })
|
35
|
+
end
|
36
|
+
end
|
@@ -0,0 +1,32 @@
|
|
1
|
+
require 'rails/generators/migration'
|
2
|
+
|
3
|
+
module PostJson
|
4
|
+
module Generators
|
5
|
+
class InstallGenerator < ::Rails::Generators::Base
|
6
|
+
include Rails::Generators::Migration
|
7
|
+
source_root File.expand_path('../templates', __FILE__)
|
8
|
+
desc "add the migrations"
|
9
|
+
|
10
|
+
def self.next_migration_number(path)
|
11
|
+
unless @prev_migration_nr
|
12
|
+
@prev_migration_nr = Time.now.utc.strftime("%Y%m%d%H%M%S").to_i
|
13
|
+
else
|
14
|
+
@prev_migration_nr += 1
|
15
|
+
end
|
16
|
+
@prev_migration_nr.to_s
|
17
|
+
end
|
18
|
+
|
19
|
+
def copy_migrations
|
20
|
+
migration_template "enable_extensions.rb", "db/migrate/enable_extensions.rb"
|
21
|
+
migration_template "create_procedures.rb", "db/migrate/create_procedures.rb"
|
22
|
+
migration_template "create_post_json_model_settings.rb", "db/migrate/create_post_json_model_settings.rb"
|
23
|
+
migration_template "create_post_json_documents.rb", "db/migrate/create_post_json_documents.rb"
|
24
|
+
migration_template "create_post_json_dynamic_indexes.rb", "db/migrate/create_post_json_dynamic_indexes.rb"
|
25
|
+
end
|
26
|
+
|
27
|
+
def copy_initializer_file
|
28
|
+
copy_file "initializer.rb", "config/initializers/post_json.rb"
|
29
|
+
end
|
30
|
+
end
|
31
|
+
end
|
32
|
+
end
|
@@ -0,0 +1,13 @@
|
|
1
|
+
class CreatePostJsonDocuments < ActiveRecord::Migration
|
2
|
+
def change
|
3
|
+
create_table :post_json_documents, id: false do |t|
|
4
|
+
t.text :id, null: false, index: true
|
5
|
+
t.integer :__doc__version
|
6
|
+
t.json :__doc__body
|
7
|
+
t.uuid :__doc__model_settings_id
|
8
|
+
end
|
9
|
+
|
10
|
+
execute "CREATE UNIQUE INDEX post_json_documents_unique_id ON post_json_documents(id, __doc__model_settings_id);"
|
11
|
+
execute "ALTER TABLE post_json_documents ADD PRIMARY KEY (id, __doc__model_settings_id);"
|
12
|
+
end
|
13
|
+
end
|
@@ -0,0 +1,18 @@
|
|
1
|
+
class CreatePostJsonModelSettings < ActiveRecord::Migration
|
2
|
+
def change
|
3
|
+
create_table :post_json_model_settings, id: :uuid do |t|
|
4
|
+
t.text :collection_name, index: true, unique: true
|
5
|
+
t.json :meta, default: {}, null: false
|
6
|
+
t.boolean :use_timestamps, default: true
|
7
|
+
t.text :created_at_attribute_name, default: 'created_at', null: false
|
8
|
+
t.text :updated_at_attribute_name, default: 'updated_at', null: false
|
9
|
+
t.boolean :include_version_number, default: true
|
10
|
+
t.text :version_attribute_name, default: 'version', null: false
|
11
|
+
t.boolean :use_dynamic_index, default: true
|
12
|
+
t.integer :create_dynamic_index_milliseconds_threshold, default: 50
|
13
|
+
t.timestamps
|
14
|
+
end
|
15
|
+
|
16
|
+
execute "CREATE INDEX post_json_model_settings_lower_collection_name ON post_json_model_settings(lower(collection_name));"
|
17
|
+
end
|
18
|
+
end
|
@@ -0,0 +1,120 @@
|
|
1
|
+
# http://pgxn.org/dist/plv8/doc/plv8.html
|
2
|
+
# http://plv8-pgopen.herokuapp.com/
|
3
|
+
# http://www.craigkerstiens.com/2013/06/25/javascript-functions-for-postgres/
|
4
|
+
# http://www.postgresonline.com/journal/archives/272-Using-PLV8-to-build-JSON-selectors.html
|
5
|
+
|
6
|
+
class CreateProcedures < ActiveRecord::Migration
|
7
|
+
def change
|
8
|
+
ActiveRecord::Base.connection.execute(json_numeric_procedure)
|
9
|
+
ActiveRecord::Base.connection.execute(json_text_procedure)
|
10
|
+
ActiveRecord::Base.connection.execute(js_filter_procedure)
|
11
|
+
ActiveRecord::Base.connection.execute(json_selector_procedure)
|
12
|
+
ActiveRecord::Base.connection.execute(json_selectors_procedure)
|
13
|
+
ActiveRecord::Base.connection.execute(show_all_indexes_procedure)
|
14
|
+
# ActiveRecord::Base.connection.execute(show_indexes_procedure)
|
15
|
+
# ActiveRecord::Base.connection.execute(ensure_dynamic_index_procedure)
|
16
|
+
end
|
17
|
+
|
18
|
+
def json_numeric_procedure
|
19
|
+
"CREATE OR REPLACE FUNCTION json_numeric(key text, data json) RETURNS numeric AS $$
|
20
|
+
if (data == null) {
|
21
|
+
return null;
|
22
|
+
}
|
23
|
+
return data[key];
|
24
|
+
$$ LANGUAGE plv8 IMMUTABLE STRICT;"
|
25
|
+
end
|
26
|
+
|
27
|
+
def json_text_procedure
|
28
|
+
"CREATE OR REPLACE FUNCTION json_text(key text, data json) RETURNS text AS $$
|
29
|
+
if (data == null) {
|
30
|
+
return null;
|
31
|
+
}
|
32
|
+
return data[key];
|
33
|
+
$$ LANGUAGE plv8 IMMUTABLE STRICT;"
|
34
|
+
end
|
35
|
+
|
36
|
+
def js_filter_procedure
|
37
|
+
"create or replace function js_filter(js_function text, json_arguments text, data json) returns numeric as $$
|
38
|
+
if (data == null) {
|
39
|
+
return null;
|
40
|
+
}
|
41
|
+
eval('var func = ' + js_function);
|
42
|
+
eval('var args = ' + (json_arguments == '' ? 'null' : json_arguments));
|
43
|
+
var final_args = [data].concat(args);
|
44
|
+
var result = func.apply(null, final_args);
|
45
|
+
return result == true || 0 < parseInt(result) ? 1 : 0;
|
46
|
+
$$ LANGUAGE plv8 IMMUTABLE STRICT;"
|
47
|
+
end
|
48
|
+
|
49
|
+
def json_selector_procedure
|
50
|
+
"CREATE OR REPLACE FUNCTION json_selector(selector text, data json) RETURNS text AS $$
|
51
|
+
if (data == null || selector == null || selector == '') {
|
52
|
+
return null;
|
53
|
+
}
|
54
|
+
var names = selector.split('.');
|
55
|
+
var result = names.reduce(function(previousValue, currentValue, index, array) {
|
56
|
+
if (previousValue == null) {
|
57
|
+
return null;
|
58
|
+
} else {
|
59
|
+
return previousValue[currentValue];
|
60
|
+
}
|
61
|
+
}, data);
|
62
|
+
return result;
|
63
|
+
$$ LANGUAGE plv8 IMMUTABLE STRICT;"
|
64
|
+
end
|
65
|
+
|
66
|
+
def json_selectors_procedure
|
67
|
+
"CREATE OR REPLACE FUNCTION json_selectors(selectors text, data json) RETURNS json AS $$
|
68
|
+
var json_selector = plv8.find_function('json_selector');
|
69
|
+
var selectorArray = selectors.replace(/\s+/g, '').split(',');
|
70
|
+
var result = selectorArray.map(function(selector) { return json_selector(selector, data); });
|
71
|
+
return result;
|
72
|
+
$$ LANGUAGE plv8 IMMUTABLE STRICT;"
|
73
|
+
end
|
74
|
+
|
75
|
+
def show_all_indexes_procedure
|
76
|
+
"CREATE OR REPLACE FUNCTION show_all_indexes() RETURNS json AS $$
|
77
|
+
var sql = \"SELECT c3.relname AS table, c2.relname AS index FROM pg_class c2 LEFT JOIN pg_index i ON c2.oid = i.indexrelid LEFT JOIN pg_class c1 ON c1.oid = i.indrelid RIGHT OUTER JOIN pg_class c3 ON c3.oid = c1.oid LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c3.relnamespace WHERE c3.relkind IN ('r','') AND n.nspname NOT IN ('pg_catalog', 'pg_toast') AND pg_catalog.pg_table_is_visible(c3.oid) ORDER BY c3.relpages DESC;\"
|
78
|
+
return plv8.execute( sql );
|
79
|
+
$$ LANGUAGE plv8 IMMUTABLE STRICT;"
|
80
|
+
end
|
81
|
+
|
82
|
+
# def show_indexes_procedure
|
83
|
+
# "CREATE OR REPLACE FUNCTION show_indexes(table_name text DEFAULT '', index_prefix text DEFAULT '') RETURNS json AS $$
|
84
|
+
# var show_all_indexes = plv8.find_function('show_all_indexes');
|
85
|
+
# var indexes = show_all_indexes();
|
86
|
+
# if (0 < (table_name || '').length) {
|
87
|
+
# indexes = indexes.filter(function(row) { return row['table'] === table_name; });
|
88
|
+
# }
|
89
|
+
# if (0 < (index_prefix || '').length) {
|
90
|
+
# indexes = indexes.filter(function(row) { return row['index'].lastIndexOf(index_prefix, 0) === 0; });
|
91
|
+
# }
|
92
|
+
# return indexes;
|
93
|
+
# $$ LANGUAGE plv8 IMMUTABLE STRICT;"
|
94
|
+
# end
|
95
|
+
|
96
|
+
# def ensure_dynamic_index_procedure
|
97
|
+
# raise ArgumentError, "index name should be: dyn_col_id_md5_hash_of_selector and truncated to a length of 63"
|
98
|
+
# raise ArgumentError, "it should only create 1 index and not multiple"
|
99
|
+
|
100
|
+
|
101
|
+
# # CREATE INDEX CONCURRENTLY post_json_documents_body_age ON post_json_documents(json_selector('age', body))
|
102
|
+
# "CREATE OR REPLACE FUNCTION ensure_dynamic_index(selectors text, collection_id text) RETURNS json AS $$
|
103
|
+
# var show_indexes = plv8.find_function('show_indexes');
|
104
|
+
# var colId = collection_id.replace('-', '');
|
105
|
+
# var indexPrefix = 'col_' + colId + '_';
|
106
|
+
# var existingIndexes = show_indexes('post_json_documents', indexPrefix).map(function(row) { return row.index; });
|
107
|
+
# var selectorArray = selectors.replace(/\s+/g, '').split(',');
|
108
|
+
|
109
|
+
# var indexes = selectorArray.map(function(selector) { return {'name': indexPrefix + selector.replace('.', '_'), selector: selector}; });
|
110
|
+
# var newIndexes = indexes.filter(function(index) { return existingIndexes.indexOf(index.name) == -1; });
|
111
|
+
|
112
|
+
# newIndexes.forEach(function(index) {
|
113
|
+
# var sql = \"CREATE INDEX \" + index.name + \" ON post_json_documents(json_selector('\" + index.selector + \"', body)) WHERE collection_id = '\" + colId + \"';\"
|
114
|
+
# plv8.execute( sql );
|
115
|
+
# });
|
116
|
+
|
117
|
+
# return newIndexes;
|
118
|
+
# $$ LANGUAGE plv8 IMMUTABLE STRICT;"
|
119
|
+
# end
|
120
|
+
end
|