activerecord-view 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 3eb9212982e304e55913df73786c1be97e279b3f
4
+ data.tar.gz: d628d7eddd62a7695dd89d266a624d397fc56e6c
5
+ SHA512:
6
+ metadata.gz: ca3eb61ad1eea56afed2d3ed734908eef9cc8d13a53c10dbea0f005c6e8fdbebb5b46815a20a17053e58f63e62a97f3302c48a876fe039a774eeff681db4d1c8
7
+ data.tar.gz: dd061a4d03f69986bd40f81d28e89630a9d262838e231db715f8459013e3775dc64f1635e14a7e968992cacab594174182e18e1fe8ec1a4e8fc9fc6d262940b0
@@ -0,0 +1,11 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
10
+ spec/internal/log/test.log
11
+ spec/internal/db/test.sqlite3
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
@@ -0,0 +1,11 @@
1
+ language: ruby
2
+ before_install: gem install bundler -v '~> 1.9'
3
+ cache: bundler
4
+ rvm:
5
+ - 2.1.3
6
+ - 2.2.1
7
+ before_script:
8
+ - mysql -e 'create database activerecord_view_test'
9
+ - psql -c 'create database activerecord_view_test' -U postgres
10
+ addons:
11
+ postgresql: "9.3"
@@ -0,0 +1,15 @@
1
+ # @markup markdown
2
+ # @title Contributor Code of Conduct
3
+ # Contributor Code of Conduct
4
+
5
+ As contributors and maintainers of this project, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities.
6
+
7
+ We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, age, or religion.
8
+
9
+ Examples of unacceptable behavior by participants include the use of sexual language or imagery, derogatory comments or personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct.
10
+
11
+ Project maintainers 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. Project maintainers who do not follow the Code of Conduct may be removed from the project team.
12
+
13
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers.
14
+
15
+ This Code of Conduct is adapted from the [Contributor Covenant](http:contributor-covenant.org), version 1.0.0, available at [http://contributor-covenant.org/version/1/0/0/](http://contributor-covenant.org/version/1/0/0/)
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in activerecord-view.gemspec
4
+ gemspec
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2015 Alexa Grey
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,139 @@
1
+ # Activerecord::View [![Build Status](https://travis-ci.org/scryptmouse/activerecord-view.svg?branch=master)](https://travis-ci.org/scryptmouse/activerecord-view)
2
+
3
+ Integration for ActiveRecord to facilitate easy use of views in migrations.
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem 'activerecord-view'
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ $ bundle
16
+
17
+ Or install it yourself as:
18
+
19
+ $ gem install activerecord-view
20
+
21
+ ## Usage
22
+
23
+ To create a view in a database migration:
24
+
25
+ ```ruby
26
+ def change
27
+ # You can provide a string
28
+ create_view :admins, 'SELECT * FROM users WHERE role = "admin"'
29
+
30
+ # Or an object that responds #to_sql
31
+ users = User.arel_table
32
+
33
+ create_view :authors, users.project('*').where(users[:role].eq('author'))
34
+
35
+ # Or a block that returns one of the above if that's more convenient
36
+ create_view :magicians do
37
+ users.project('*').where(users[:role].eq('magician'))
38
+ end
39
+ end
40
+ ```
41
+
42
+ Use with `change` is fully supported, commands will revert and do the right thing.
43
+
44
+ Reverting a `drop_view` requires you to pass the body to restore somehow:
45
+
46
+ ```
47
+ def change
48
+ drop_view :authors, original_authors_definition_from_elsewhere
49
+
50
+ drop_view :admins do
51
+ original_admins_definition_from_elsewhere
52
+ end
53
+
54
+ # In a change method, this will raise an ActiveRecord::IrreversibleMigration!
55
+ drop_view :magicians
56
+ end
57
+ ```
58
+
59
+ Then, in your model
60
+
61
+ ```ruby
62
+ class Magician < ActiveRecord::Base
63
+ is_view!
64
+ end
65
+ ```
66
+
67
+ By default, views are made read-only. [MySQL](https://dev.mysql.com/doc/refman/5.5/en/view-updatability.html) and
68
+ [Postgres](http://www.postgresql.org/docs/9.3/static/sql-createview.html#SQL-CREATEVIEW-UPDATABLE-VIEWS) support
69
+ the notion of updatable views, but this currently isn't tested.
70
+
71
+ If you want to make a view updatable:
72
+
73
+ ```ruby
74
+ class Magician < ActiveRecord::Base
75
+ is_view! readonly: false
76
+ end
77
+ ```
78
+
79
+ ### Materialized Views
80
+ Postgres supports [materialized views](http://www.postgresql.org/docs/9.3/static/rules-materializedviews.html), and so does this gem.
81
+
82
+ ```ruby
83
+ def change
84
+ users = User.arel_table
85
+
86
+ by_role = ->(role) { users.project('*').where(users[:role].eq('admin')) }
87
+
88
+ # The API is basically the same
89
+ create_materialized_view :admins do
90
+ by_role.call 'admin'
91
+ end
92
+
93
+ # Except there's the option to pass `with_data: true` to prepopulate the view.
94
+ create_materialized_view :authors, with_data: true do
95
+ by_role.call 'author'
96
+ end
97
+
98
+ create_materialized_view :magicians, by_role['magician'], with_data: true
99
+
100
+ # Materialized views support indexing
101
+ add_index :admins, :name
102
+ add_index :magicians, :name
103
+ add_index :authors, :email, unique: true
104
+ end
105
+ ```
106
+
107
+ Then, in your model:
108
+
109
+ ```ruby
110
+ class Author < ActiveRecord::Base
111
+ is_materialized_view!
112
+ end
113
+ ```
114
+
115
+ Like regular views above, materialized views can also be made updatable on MySQL and Postgres
116
+ if the conditions are met, via `is_materialized_view! readonly: false`.
117
+
118
+ To refresh a materialized view, use `ModelName.refresh_view!`.
119
+
120
+ Concurrent refresh (PG 9.4) is not yet supported through the gem, but it is on the roadmap.
121
+
122
+ ## Requirements
123
+
124
+ * Ruby 2.1+
125
+ * ActiveRecord 4.1+
126
+
127
+ ## Development
128
+
129
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `bin/console` for an interactive prompt that will allow you to experiment.
130
+
131
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release` to create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
132
+
133
+ ## Contributing
134
+
135
+ 1. Fork it ( https://github.com/scryptmouse/activerecord-view/fork )
136
+ 2. Create your feature branch (`git checkout -b my-new-feature`)
137
+ 3. Commit your changes (`git commit -am 'Add some feature'`)
138
+ 4. Push to the branch (`git push origin my-new-feature`)
139
+ 5. Create a new Pull Request
@@ -0,0 +1,12 @@
1
+ require "bundler/gem_tasks"
2
+
3
+ begin
4
+ require 'rspec/core/rake_task'
5
+
6
+ RSpec::Core::RakeTask.new(:spec) do |t|
7
+ t.verbose = false
8
+ end
9
+ rescue LoadError
10
+ end
11
+
12
+ task :default => :spec
@@ -0,0 +1,36 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'activerecord/view/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "activerecord-view"
8
+ spec.version = ActiveRecord::View::VERSION
9
+ spec.authors = ["Alexa Grey"]
10
+ spec.email = ["devel@mouse.vc"]
11
+
12
+ spec.summary = %q{SQL views with ActiveRecord}
13
+ spec.description = %q{SQL views with ActiveRecord}
14
+ spec.homepage = "https://github.com/scryptmouse/activerecord-view"
15
+
16
+ spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
17
+ spec.bindir = "exe"
18
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
19
+ spec.require_paths = ["lib"]
20
+ spec.required_ruby_version = '~> 2.1'
21
+
22
+ spec.add_dependency "activerecord", "> 4.1", "< 5"
23
+ spec.add_dependency "dux"
24
+ spec.add_dependency "virtus", "~> 1.0"
25
+
26
+ spec.add_development_dependency "bundler", "~> 1.9"
27
+ spec.add_development_dependency "rake", "~> 10.0"
28
+ spec.add_development_dependency "combustion"
29
+ spec.add_development_dependency "database_cleaner"
30
+ spec.add_development_dependency "rspec"
31
+ spec.add_development_dependency "pry"
32
+ spec.add_development_dependency "mysql2"
33
+ spec.add_development_dependency "sqlite3"
34
+ spec.add_development_dependency "pg"
35
+ spec.add_development_dependency "simplecov"
36
+ end
@@ -0,0 +1,18 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ ENV['RAILS_ENV'] ||= 'test'
4
+
5
+ require "bundler/setup"
6
+ require "activerecord/view"
7
+ require "combustion"
8
+ require "pry"
9
+
10
+ Combustion.initialize! :active_record
11
+
12
+ begin
13
+ TEST_MODELS.each(&:create_view!)
14
+
15
+ Pry.start
16
+ ensure
17
+ TEST_MODELS.each(&:drop_view!)
18
+ end
@@ -0,0 +1,10 @@
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+
5
+ bundle install
6
+
7
+ # Do any other automated setup that you need to do here
8
+
9
+ createdb -U postgres activerecord_view_test
10
+ mysql -e 'create database activerecord_view_test'
@@ -0,0 +1 @@
1
+ require 'activerecord/view'
@@ -0,0 +1,28 @@
1
+ require 'bundler/setup'
2
+
3
+ require "active_record"
4
+ require "virtus"
5
+ require "dux"
6
+ require "activerecord/view/error"
7
+ require "activerecord/view/utility"
8
+ require "activerecord/view/version"
9
+
10
+ require 'activerecord/view/introspection'
11
+
12
+ require 'activerecord/view/integration'
13
+
14
+ require 'activerecord/view/read_only'
15
+ require 'activerecord/view/view_methods'
16
+ require 'activerecord/view/materialized_view_methods'
17
+
18
+ module ActiveRecord
19
+ module View
20
+ extend ActiveSupport::Concern
21
+ extend Integration
22
+ extend Introspection
23
+ end
24
+ end
25
+
26
+ ActiveSupport.on_load :active_record do
27
+ ActiveRecord::View.enable!
28
+ end
@@ -0,0 +1,19 @@
1
+ module ActiveRecord
2
+ module View
3
+ # @api private
4
+ class Error < StandardError; end
5
+
6
+ # @api private
7
+ class MaterializedViewNotSupported < Error
8
+ def initialize(adapter)
9
+ super("Materialized views are not supported by `#{adapter}`")
10
+ end
11
+ end
12
+
13
+ # @api private
14
+ class UnsupportedDatabase < Error; end
15
+
16
+ # @api private
17
+ class UnsupportedSyntax < ActiveRecord::View::Error; end
18
+ end
19
+ end
@@ -0,0 +1,38 @@
1
+ module ActiveRecord
2
+ module View
3
+ module Integration
4
+ AR_INCLUSIONS = {
5
+ 'SchemaMethods' => 'ActiveRecord::ConnectionAdapters::AbstractAdapter',
6
+ 'CommandRecorderMethods' => 'ActiveRecord::Migration::CommandRecorder'
7
+ }
8
+
9
+ AR_EXTENSIONS = {
10
+ 'ModelMethods' => 'ActiveRecord::Base'
11
+ }
12
+
13
+ def enable!
14
+ AR_INCLUSIONS.each do |mod_name, target|
15
+ target_klass = target.constantize
16
+ mod = "ActiveRecord::View::Integration::#{mod_name}".constantize
17
+
18
+ target_klass.include mod
19
+ end
20
+
21
+ AR_EXTENSIONS.each do |mod_name, target|
22
+ target_klass = target.constantize
23
+ mod = "ActiveRecord::View::Integration::#{mod_name}".constantize
24
+
25
+ target_klass.extend mod
26
+ end
27
+
28
+ #ActiveRecord::ConnectionAdapters::AbstractAdapter.include ActiveRecord::View::Integration::SchemaMethods
29
+ #ActiveRecord::Base.extend ActiveRecord::View::Integration::ModelMethods
30
+ #ActiveRecord::Migration::CommandRecorder.include ActiveRecord::View::
31
+ end
32
+
33
+ require_relative './integration/command_recorder_methods'
34
+ require_relative './integration/model_methods'
35
+ require_relative './integration/schema_methods'
36
+ end
37
+ end
38
+ end
@@ -0,0 +1,61 @@
1
+ module ActiveRecord
2
+ module View
3
+ module Integration
4
+ module CommandRecorderMethods
5
+ CREATE_VIEW_METHODS = %i[create_view create_materialized_view]
6
+
7
+ DROP_VIEW_METHODS = %i[drop_view drop_materialized_view]
8
+
9
+ VIEW_METHOD_PAIRS = Hash[CREATE_VIEW_METHODS.zip(DROP_VIEW_METHODS)].tap do |hsh|
10
+ hsh.merge!(hsh.invert)
11
+ end
12
+
13
+ VIEW_METHODS = CREATE_VIEW_METHODS + DROP_VIEW_METHODS
14
+
15
+ VIEW_METHODS.each do |method_name|
16
+ class_eval <<-RUBY, __FILE__, __LINE__ + 1
17
+ def #{method_name}(*args, &block)
18
+ record(:#{method_name}, args, &block)
19
+ end
20
+ RUBY
21
+ end
22
+
23
+ CREATE_VIEW_METHODS.each do |method_name|
24
+ inverse_method = VIEW_METHOD_PAIRS.fetch method_name
25
+
26
+ class_eval <<-RUBY, __FILE__, __LINE__ + 1
27
+ def invert_#{method_name}(args, &block)
28
+ view_name = args.first
29
+
30
+ [:#{inverse_method}, [view_name]]
31
+ end
32
+ RUBY
33
+ end
34
+
35
+ DROP_VIEW_METHODS.each do |method_name|
36
+ inverse_method = VIEW_METHOD_PAIRS.fetch method_name
37
+
38
+ class_eval <<-RUBY, __FILE__, __LINE__ + 1
39
+ def invert_#{method_name}(args, &block)
40
+ options = args.extract_options!
41
+
42
+ view_name = args.shift
43
+ view_body = ActiveRecord::View.validate_body(args.shift, &block)
44
+
45
+
46
+ unless view_body.present? || block_given?
47
+ raise ActiveRecord::IrreversibleMigration, "To avoid mistakes, #{method_name} is only reversible if provided with a view body or a block."
48
+ end
49
+
50
+ args = [view_name]
51
+ args << view_body if view_body.present?
52
+ args << options
53
+
54
+ [:#{inverse_method}, args, block]
55
+ end
56
+ RUBY
57
+ end
58
+ end
59
+ end
60
+ end
61
+ end