pg_activerecord_enum 0.0.7

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 16f4a5bbf1734048bd67184750467bcb6c2f9eaf
4
+ data.tar.gz: eb092b571eed066c3d6fd4b211b1dfaa7217c82e
5
+ SHA512:
6
+ metadata.gz: 3c0fb8ff250c43d2405c94fdb772e1fc2b4fa005e78ca2e83b4c218df1c48350ee7885c15c23795eafba0efed6c8a329639e4796487a2cf897927f6bbed88499
7
+ data.tar.gz: 94d0b339d143a3ff3b78ec17568b734601167ad3c229858182c7c42a155a2f9f59b83f1de136ac6a0d85d9ac06ad8d5e0c3de250b1840cb8c98e583463b074f2
data/.gitignore ADDED
@@ -0,0 +1,11 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.travis.yml ADDED
@@ -0,0 +1,5 @@
1
+ sudo: false
2
+ language: ruby
3
+ rvm:
4
+ - 2.3.3
5
+ before_install: gem install bundler -v 1.16.0
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source "https://rubygems.org"
2
+
3
+ git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2018 inpego
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.
data/README.md ADDED
@@ -0,0 +1,121 @@
1
+ # PgActiveRecordEnum
2
+
3
+ Integration of PostgreSQL native enums with ActiveRecord enums.
4
+
5
+ ## Motivation
6
+
7
+ 1. All the activerecord enum's abilities out of the box.
8
+ 2. All schema definitions are placed inside migrations, not inside models. That makes code cleaner and eliminates the possibility to accidentally change model's enum definition even if it's defined via hash.
9
+ 3. All the enums changes may be followed by migrations timestamps. If enum is defined inside model, it's changes may be investigated only through source control, which is far less convenient.
10
+ 4. Performance degrade could hardly be noticed, 'cause PostgreSQL uses four-byte integers to provide enums internally.
11
+ 5. Data validation is carried out by database itself. That makes it impossible to write inconsistent values via `update_column` or `update_all` method calls, which is an issue when using original activerecord enums, or even working with the database directly.
12
+ 6. The last but not least, all the enum's values are displayed with their original values when working with the database via console or GUI client. No need to look into the code base to find out which number stands for which value.
13
+
14
+
15
+ ## Installation
16
+
17
+ Add this line to your application's Gemfile:
18
+
19
+ ```ruby
20
+ gem 'pg_activerecord_enum'
21
+ ```
22
+
23
+ And then execute:
24
+
25
+ $ bundle
26
+
27
+ Or install it yourself as:
28
+
29
+ $ gem install pg_activerecord_enum
30
+
31
+ ## Usage
32
+
33
+ Migration:
34
+
35
+ ```ruby
36
+ class CreateFruits < ActiveRecord::Migration[5.1]
37
+ def change
38
+ create_table :fruits do |t|
39
+ t.enum :fruit_type, values: %i[banana orange grape], allow_blank: true
40
+ t.timestamps
41
+ end
42
+ end
43
+ end
44
+ ```
45
+
46
+ Or for existing table:
47
+
48
+ ```ruby
49
+ class CreateFruits < ActiveRecord::Migration[5.1]
50
+ def change
51
+ add_enum :fruits, :color, values: %i[red green yellow], allow_blank: true
52
+ end
53
+ end
54
+ ```
55
+
56
+ **allow_blank** adds empty value to enum.
57
+
58
+ **Note:** migration rollback will remove enums only if other tables do not depend on them.
59
+
60
+ Model:
61
+
62
+ ```ruby
63
+ class Fruit < ApplicationRecord
64
+ pg_enum :fruit_type
65
+ pg_enum :color
66
+ end
67
+ ```
68
+
69
+ ```ruby
70
+ Fruit.banana.count # 0
71
+ banana = Fruit.banana.create
72
+ banana.yellow!
73
+ banana.banana? # true
74
+ banana.color # "yellow"
75
+ banana.grape! #
76
+ banana.grape? # true
77
+ Fruit.grape.count # 1
78
+ ```
79
+
80
+ In PostgreSQL DB:
81
+ ```
82
+ # select * from fruits;
83
+ id | fruit_type | created_at | updated_at | color
84
+ ----+------------+----------------------------+----------------------------+--------
85
+ 1 | grape | 2018-02-19 04:07:20.548005 | 2018-02-19 04:07:20.554754 | yellow
86
+ (1 row)
87
+
88
+ =# \dT+ fruit_type;
89
+ List of data types
90
+ Schema | Name | Internal name | Size | Elements | Owner | Access privileges | Description
91
+ --------+------------+---------------+------+----------+----------+-------------------+-------------
92
+ public | fruit_type | fruit_type | 4 | banana +| postgres | |
93
+ | | | | orange +| | |
94
+ | | | | grape +| | |
95
+ | | | | | | |
96
+ (1 row)
97
+
98
+ =# \dT+ color;
99
+ List of data types
100
+ Schema | Name | Internal name | Size | Elements | Owner | Access privileges | Description
101
+ --------+-------+---------------+------+----------+----------+-------------------+-------------
102
+ public | color | color | 4 | red +| postgres | |
103
+ | | | | green +| | |
104
+ | | | | yellow +| | |
105
+ | | | | | | |
106
+ (1 row)
107
+ ```
108
+
109
+ ## Development
110
+
111
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
112
+
113
+ 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`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
114
+
115
+ ## Contributing
116
+
117
+ Bug reports and pull requests are welcome on GitHub at https://github.com/inpego/pg_activerecord_enum.
118
+
119
+ ## License
120
+
121
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
@@ -0,0 +1,81 @@
1
+ module PgActiveRecordEnum
2
+ module Schema
3
+ def self.include_migrations
4
+ ActiveRecord::ConnectionAdapters::Table.send :include, TableDefinition
5
+ ActiveRecord::ConnectionAdapters::TableDefinition.send :include, TableDefinition
6
+ ActiveRecord::ConnectionAdapters::AbstractAdapter.send :include, Statements
7
+ ActiveRecord::Migration::CommandRecorder.send :include, CommandRecorder
8
+ end
9
+
10
+ module Statements
11
+ def add_enum(table_name, *enum_names)
12
+ raise ArgumentError, 'Please specify enum name in your add_enum call in your migration.' if enum_names.empty?
13
+
14
+ options = enum_names.extract_options!
15
+ values = options.delete(:values)
16
+
17
+ raise ArgumentError, 'Please specify values for enum in your migration.' if values.blank?
18
+
19
+ enum_names.each do |enum_name|
20
+ PgActiveRecordEnum.define enum_name, values, options
21
+ add_column(table_name, enum_name, enum_name, options)
22
+ end
23
+ end
24
+
25
+ def remove_enum(table_name, *enum_names)
26
+ raise ArgumentError, 'Please specify enum name in your add_enum call in your migration.' if enum_names.empty?
27
+
28
+ enum_names.extract_options!
29
+
30
+ enum_names.each do |enum_name|
31
+ remove_column(table_name, enum_name)
32
+ PgActiveRecordEnum.drop enum_name
33
+ end
34
+ end
35
+
36
+ def drop_table_with_enums(table_name, enums, *args, &block)
37
+ drop_table(table_name, *args, &block)
38
+ enums.each { |enum_name| PgActiveRecordEnum.drop enum_name }
39
+ end
40
+ end
41
+
42
+ module TableDefinition
43
+ def enum(*enum_names)
44
+ options = enum_names.extract_options!
45
+ values = options.delete(:values)
46
+
47
+ raise ArgumentError, 'Please specify values for enum in your migration.' if values.blank?
48
+
49
+ enum_names.each do |enum_name|
50
+ PgActiveRecordEnum.define enum_name, values, options
51
+ column(enum_name, enum_name, options)
52
+ end
53
+ end
54
+ end
55
+
56
+ module CommandRecorder
57
+ def add_enum(*args)
58
+ record(:add_enum, args)
59
+ end
60
+
61
+ private
62
+
63
+ def invert_create_table(args)
64
+ table_name = args.first
65
+ enums = ActiveRecord::Base.connection.columns(table_name).select do |column|
66
+ column.sql_type_metadata.type == :enum
67
+ end
68
+ if enums.present?
69
+ args.shift
70
+ [:drop_table_with_enums, [table_name, enums.map(&:name)] + args]
71
+ else
72
+ [:drop_table, args]
73
+ end
74
+ end
75
+
76
+ def invert_add_enum(args)
77
+ [:remove_enum, args]
78
+ end
79
+ end
80
+ end
81
+ end
@@ -0,0 +1,3 @@
1
+ module PgActiveRecordEnum
2
+ VERSION = '0.0.7'
3
+ end
@@ -0,0 +1,79 @@
1
+ require 'pg_activerecord_enum/version'
2
+ require 'pg_activerecord_enum/schema'
3
+
4
+ module PgActiveRecordEnum
5
+ def self.define(name, values, options = {})
6
+ values << '' if options[:allow_blank]
7
+ return if values.blank?
8
+ values.map!(&:to_s)
9
+ previously_defined = values_for(name)
10
+ if previously_defined.present? && previously_defined.sort != values.sort
11
+ raise ArgumentError, "Enum `#{name}` already defined with other values: " +
12
+ "#{_j(previously_defined)} (#{_j(values)} supplied)."
13
+ elsif previously_defined.blank?
14
+ ActiveRecord::Base.connection.execute("CREATE TYPE #{name} AS ENUM (#{_j(values)});")
15
+ else
16
+ ActiveRecord::Base.logger.info "Enum `#{name}` with same values already defined, skip."
17
+ end
18
+ end
19
+
20
+ def self.drop(name, options = {})
21
+ enum_dependencies = dependencies(name)
22
+ if enum_dependencies.present?
23
+ if options[:cascade]
24
+ ActiveRecord::Base.connection.execute("DROP TYPE #{name} CASCADE;")
25
+ else
26
+ ActiveRecord::Base.logger.warn "Other objects (#{_j(enum_dependencies)}) depend on enum `#{name}`, skip."
27
+ end
28
+ else
29
+ ActiveRecord::Base.connection.execute("DROP TYPE IF EXISTS #{name};")
30
+ end
31
+ end
32
+
33
+ def self.change(name, values, options = {})
34
+ drop(name)
35
+ define(name, values, options)
36
+ end
37
+
38
+ def self.add_values(name, values)
39
+ values.each do |value|
40
+ ActiveRecord::Base.connection.execute("ALTER TYPE #{name} ADD VALUE '#{value}';")
41
+ end
42
+ end
43
+
44
+ def self.allow_blank_for(name)
45
+ add_values(name, [''])
46
+ end
47
+
48
+ def self.values_for(name)
49
+ enum_values_sql = <<-SQL
50
+ SELECT e.enumlabel AS enum_value
51
+ FROM pg_type t
52
+ JOIN pg_enum e ON t.oid = e.enumtypid
53
+ JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace
54
+ WHERE t.typname = '#{name}'
55
+ SQL
56
+ ActiveRecord::Base.connection.execute(enum_values_sql).map { |row| row['enum_value'] }
57
+ end
58
+
59
+ def self.dependencies(name)
60
+ ActiveRecord::Base.connection.execute(
61
+ 'SELECT objid::regclass::text FROM pg_depend ' +
62
+ "WHERE classid = 'pg_class'::regclass AND refobjid::regtype::text = '#{name}';"
63
+ ).to_a.map(&:values).flatten
64
+ end
65
+
66
+ def self._j(values)
67
+ "'#{values.join("', '")}'"
68
+ end
69
+
70
+ def pg_enum(name)
71
+ enum_values = PgActiveRecordEnum.values_for(name).reject(&:blank?)
72
+ enum name => enum_values.zip(enum_values).to_h
73
+ end
74
+ end
75
+
76
+ require 'active_support/all'
77
+ require 'active_record'
78
+ ActiveRecord::Base.send :extend, PgActiveRecordEnum
79
+ PgActiveRecordEnum::Schema.include_migrations
@@ -0,0 +1,37 @@
1
+
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'pg_activerecord_enum/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = 'pg_activerecord_enum'
8
+ spec.version = PgActiveRecordEnum::VERSION
9
+ spec.authors = ['inpego']
10
+ spec.email = 'inpego@mail.ru'
11
+
12
+ spec.summary = %q{Gem that integrates PostgreSQL native enums with ActiveRecord enums.}
13
+ spec.homepage = 'https://github.com/inpego/pg_activerecord_enum'
14
+ spec.license = 'MIT'
15
+
16
+ # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
17
+ # to allow pushing to a single host or delete this section to allow pushing to any host.
18
+ if spec.respond_to?(:metadata)
19
+ spec.metadata['allowed_push_host'] = 'https://rubygems.org'
20
+ else
21
+ raise 'RubyGems 2.0 or newer is required to protect against ' \
22
+ 'public gem pushes.'
23
+ end
24
+
25
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
26
+ f.match(%r{^(test|spec|features)/})
27
+ end
28
+ spec.require_paths = ['lib']
29
+
30
+ spec.add_development_dependency 'bundler', '~> 1.16'
31
+ spec.add_development_dependency 'rake', '~> 10.0'
32
+ spec.add_development_dependency 'rspec', '~> 3.0'
33
+
34
+ spec.add_runtime_dependency 'activerecord', '>= 4.1.8'
35
+ spec.add_runtime_dependency 'activesupport', '>= 4.1.8'
36
+ spec.add_runtime_dependency 'pg'
37
+ end
metadata ADDED
@@ -0,0 +1,139 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: pg_activerecord_enum
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.7
5
+ platform: ruby
6
+ authors:
7
+ - inpego
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2018-02-20 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.16'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.16'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '10.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '10.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rspec
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '3.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '3.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: activerecord
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: 4.1.8
62
+ type: :runtime
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: 4.1.8
69
+ - !ruby/object:Gem::Dependency
70
+ name: activesupport
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - ">="
74
+ - !ruby/object:Gem::Version
75
+ version: 4.1.8
76
+ type: :runtime
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - ">="
81
+ - !ruby/object:Gem::Version
82
+ version: 4.1.8
83
+ - !ruby/object:Gem::Dependency
84
+ name: pg
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - ">="
88
+ - !ruby/object:Gem::Version
89
+ version: '0'
90
+ type: :runtime
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - ">="
95
+ - !ruby/object:Gem::Version
96
+ version: '0'
97
+ description:
98
+ email: inpego@mail.ru
99
+ executables: []
100
+ extensions: []
101
+ extra_rdoc_files: []
102
+ files:
103
+ - ".gitignore"
104
+ - ".rspec"
105
+ - ".travis.yml"
106
+ - Gemfile
107
+ - LICENSE.txt
108
+ - README.md
109
+ - Rakefile
110
+ - lib/pg_activerecord_enum.rb
111
+ - lib/pg_activerecord_enum/schema.rb
112
+ - lib/pg_activerecord_enum/version.rb
113
+ - pg_activerecord_enum.gemspec
114
+ homepage: https://github.com/inpego/pg_activerecord_enum
115
+ licenses:
116
+ - MIT
117
+ metadata:
118
+ allowed_push_host: https://rubygems.org
119
+ post_install_message:
120
+ rdoc_options: []
121
+ require_paths:
122
+ - lib
123
+ required_ruby_version: !ruby/object:Gem::Requirement
124
+ requirements:
125
+ - - ">="
126
+ - !ruby/object:Gem::Version
127
+ version: '0'
128
+ required_rubygems_version: !ruby/object:Gem::Requirement
129
+ requirements:
130
+ - - ">="
131
+ - !ruby/object:Gem::Version
132
+ version: '0'
133
+ requirements: []
134
+ rubyforge_project:
135
+ rubygems_version: 2.6.13
136
+ signing_key:
137
+ specification_version: 4
138
+ summary: Gem that integrates PostgreSQL native enums with ActiveRecord enums.
139
+ test_files: []