rails-pg_trigger 0.1.0

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
+ SHA256:
3
+ metadata.gz: 4d272414038e590f0a426449fa3ed1072a6f8d7706603e745c08bad04c7222a2
4
+ data.tar.gz: 364c89e5ecc7736df8997a74a324f8d784a7a692b958bf9ad799407aa588f0a8
5
+ SHA512:
6
+ metadata.gz: 2454620e450678dbe9e63efc27735a7f632d33ef9c527edbe9da90b53667a2df12a578bd3c49ddfc489a88f92cd4954f593e37ec89abca2033794a5cb1262154
7
+ data.tar.gz: 53f38eb069859f13b5d43cf79dbf1ed32e3391d0e1d346ae5e6f8961b24f142e831e919ae5755ddb763b60acb8d1f3c09aabcb2025a229b1491394c14a68001d
data/.standard.yml ADDED
@@ -0,0 +1,3 @@
1
+ # For available configuration options, see:
2
+ # https://github.com/testdouble/standard
3
+ ruby_version: 2.6
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2024-01-04
4
+
5
+ - Initial release
@@ -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 cocchi.c@gmail.com. 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/Gemfile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in rails-pg_trigger.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+
10
+ gem "minitest", "~> 5.0"
11
+
12
+ gem "standard", "~> 1.3"
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024 ccocchi
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,37 @@
1
+ # Rails::PgTrigger
2
+
3
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/rails/pg_trigger`. To experiment with that code, run `bin/console` for an interactive prompt.
4
+
5
+ TODO: Delete this and the text above, and describe your gem
6
+
7
+ ## Installation
8
+
9
+ Install the gem and add to the application's Gemfile by executing:
10
+
11
+ $ bundle add rails-pg_trigger
12
+
13
+ If bundler is not being used to manage dependencies, install the gem by executing:
14
+
15
+ $ gem install rails-pg_trigger
16
+
17
+ ## Usage
18
+
19
+ TODO: Write usage instructions here
20
+
21
+ ## Development
22
+
23
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
24
+
25
+ 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 the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
26
+
27
+ ## Contributing
28
+
29
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/rails-pg_trigger. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/[USERNAME]/rails-pg_trigger/blob/master/CODE_OF_CONDUCT.md).
30
+
31
+ ## License
32
+
33
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
34
+
35
+ ## Code of Conduct
36
+
37
+ Everyone interacting in the Rails::PgTrigger project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/rails-pg_trigger/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rake/testtask"
5
+
6
+ Rake::TestTask.new(:test) do |t|
7
+ t.libs << "test"
8
+ t.libs << "lib"
9
+ t.test_files = FileList["test/**/test_*.rb"]
10
+ end
11
+
12
+ require "standard/rake"
13
+
14
+ task default: %i[test standard]
@@ -0,0 +1,15 @@
1
+ module ActiveRecord
2
+ module TriggerHelpers
3
+ def create_trigger(name, content)
4
+ say_with_time("create_trigger(#{name})") do
5
+ connection.execute(content)
6
+ end
7
+ end
8
+
9
+ def drop_trigger(name, content)
10
+ say_with_time("drop_trigger(#{name})") do
11
+ connection.execute(content)
12
+ end
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,111 @@
1
+ require_relative "indented_string"
2
+ require_relative "model"
3
+ require_relative "plan"
4
+ require_relative "scanner"
5
+
6
+ module PgTrigger
7
+ module Generator
8
+ class << self
9
+ def run(models:)
10
+ triggers = models.filter_map { |m| m._triggers.presence }.flatten
11
+ scanner = Scanner.new(File.read(PgTrigger.structure_file_path))
12
+ existing = scanner.triggers
13
+
14
+ plan = Plan::Builder.new(triggers, existing).result
15
+ return if plan.empty?
16
+
17
+ migration = Migration.new(plan)
18
+ migration.save_to_file
19
+ migration.name
20
+ end
21
+ end
22
+
23
+ class Migration
24
+ attr_reader :name
25
+
26
+ def initialize(plan)
27
+ @plan = plan
28
+ @output = nil
29
+
30
+ number = ActiveRecord::Migration.next_migration_number(0)
31
+ @name = "#{number}_#{plan.name}.rb"
32
+ end
33
+
34
+ def save_to_file
35
+ generate_output if @output.nil?
36
+
37
+ filename = name
38
+ File.binwrite(File.join(PgTrigger.migrations_path, filename), @output)
39
+
40
+ filename
41
+ end
42
+
43
+ def generate_output
44
+ @output = ""
45
+ header
46
+ up(:up)
47
+ @output << "\n"
48
+ up(:down)
49
+ footer
50
+ end
51
+
52
+ private
53
+
54
+ def header
55
+ migration_name = @plan.name.camelize
56
+
57
+ @output << "# This migration was auto-generated via `rake db:triggers:migration'.\n\n"
58
+ @output << "class #{migration_name} < ActiveRecord::Migration[#{ActiveRecord::Migration.current_version}]\n"
59
+ end
60
+
61
+ def up(dir)
62
+ res = IndentedString.new(size: 2, initial_indent: true)
63
+ res << "def #{dir}\n"
64
+ res.indent!
65
+
66
+ create = ->(t) do
67
+ add_command("create_trigger", t) do |s|
68
+ if t.create_function?
69
+ s += t.create_function_sql
70
+ s.newline
71
+ end
72
+ s += t.create_trigger_sql
73
+ end
74
+ end
75
+
76
+ drop = ->(t) do
77
+ add_command("drop_trigger", t) do |s|
78
+ s += t.drop_trigger_sql
79
+ s.newline
80
+ if t.create_function?
81
+ s += t.drop_function_sql
82
+ end
83
+ end
84
+ end
85
+
86
+ blocks = @plan.new_triggers.map { |t| (dir == :up ? create : drop).call(t) }
87
+ blocks.concat @plan.removed_triggers.map { |t| (dir == :up ? drop : create).call(t) }
88
+
89
+ res += blocks.join("\n")
90
+ res.outdent!
91
+ res << "end\n"
92
+ @output << res.to_s
93
+ end
94
+
95
+ def footer
96
+ @output << "end\n"
97
+ end
98
+
99
+ def add_command(cmd, t)
100
+ res = IndentedString.new(size: 0)
101
+ res << %{#{cmd} "#{t.name}", <<~SQL\n}
102
+ res.indent!
103
+ yield res
104
+ res.outdent!
105
+ res.newline
106
+ res << "SQL\n"
107
+ res.to_s
108
+ end
109
+ end
110
+ end
111
+ end
@@ -0,0 +1,58 @@
1
+ # frozen_string_literal: true
2
+
3
+ class PgTrigger::IndentedString
4
+ def initialize(size:, initial_indent: true)
5
+ @spaces = " " * size
6
+ @inner = +""
7
+ @start = initial_indent
8
+ end
9
+
10
+ def indent!
11
+ @spaces << " "
12
+ end
13
+
14
+ def outdent!
15
+ @spaces.slice!(-2, 2)
16
+ end
17
+
18
+ def append(str)
19
+ @inner << @spaces << str
20
+ self
21
+ end
22
+ alias_method :<<, :append
23
+
24
+ def +(str)
25
+ str.each_line do |l|
26
+ if l == "\n"
27
+ @inner << l
28
+ else
29
+ @inner << @spaces << l
30
+ end
31
+ end
32
+ self
33
+ end
34
+
35
+ def newline
36
+ @inner << "\n"
37
+ end
38
+
39
+ # def append_raw_string(str, newline: true)
40
+ # endline if newline
41
+ # self
42
+ # end
43
+
44
+ # def append_newline(str)
45
+ # @inner << @spaces << str
46
+ # endline
47
+ # end
48
+ # alias_method :<<, :append_newline
49
+
50
+ # def endline
51
+ # @inner << "\n"
52
+ # self
53
+ # end
54
+
55
+ def to_s = @inner
56
+
57
+ alias_method :to_str, :to_s
58
+ end
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "trigger"
4
+
5
+ module PgTrigger::Model
6
+ def self.included(other)
7
+ other.extend ClassMethods
8
+ end
9
+
10
+ module ClassMethods
11
+ attr_reader :_triggers
12
+
13
+ def trigger
14
+ tr = PgTrigger::Trigger.new
15
+ tr.on(table_name)
16
+
17
+ @_triggers ||= []
18
+ @_triggers << tr
19
+ tr
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,10 @@
1
+ module PgTrigger::Noop
2
+ def self.included(other)
3
+ other.extend ClassMethods
4
+ end
5
+
6
+ module ClassMethods
7
+ def trigger
8
+ end
9
+ end
10
+ end
@@ -0,0 +1,110 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "trigger"
4
+
5
+ module PgTrigger
6
+ # This class represents the actions needed to go from the existing triggers to
7
+ # the expected triggers defined in the models.
8
+ #
9
+ class Plan
10
+ class Builder
11
+ def initialize(expected, existing)
12
+ @expected = expected
13
+ @existing = existing
14
+ end
15
+
16
+ def result
17
+ plan = Plan.new
18
+
19
+ # Find new or updated triggers
20
+ @expected.each do |t|
21
+ e = @existing.find { |_t| _t.name == t.name }
22
+ if e
23
+ plan.update_trigger(t) unless t.same_content_as?(e)
24
+ else
25
+ plan.add_trigger(t)
26
+ end
27
+ end
28
+
29
+ # Find removed triggers
30
+ @existing.each do |e|
31
+ next if @expected.any? { |t| t.name == e.name }
32
+ plan.drop_trigger(e)
33
+ end
34
+
35
+ plan
36
+ end
37
+ end
38
+
39
+ attr_reader :type, :table
40
+
41
+ def initialize
42
+ @name = nil
43
+ @type = nil
44
+ @table = nil
45
+ @actions = Hash.new { |h, k| h[k] = [] }.tap(&:compare_by_identity)
46
+ end
47
+
48
+ def new_triggers = @actions[:to_add]
49
+
50
+ def removed_triggers = @actions[:to_remove]
51
+
52
+ def empty? = @actions.empty?
53
+
54
+ def name
55
+ @name ||= begin
56
+ action = case type
57
+ when :create then "create"
58
+ when :drop then "drop"
59
+ when :update then "update"
60
+ else
61
+ "change"
62
+ end
63
+
64
+ table_name = table == "multiple" ? "multiple_tables" : table
65
+
66
+ "#{action}_triggers_on_#{table_name}"
67
+ end
68
+ end
69
+
70
+ def add_trigger(t)
71
+ set_type :create
72
+ set_table t.table
73
+
74
+ @actions[:to_add] << t
75
+ end
76
+
77
+ def drop_trigger(t)
78
+ set_type :drop
79
+ set_table t.table
80
+
81
+ @actions[:to_remove] << t
82
+ end
83
+
84
+ def update_trigger(t)
85
+ set_type :update
86
+ set_table t.table
87
+
88
+ @actions[:to_remove] << t
89
+ @actions[:to_add] << t
90
+ end
91
+
92
+ private
93
+
94
+ def set_type(type)
95
+ if @type
96
+ @type = :multi if @type != type
97
+ else
98
+ @type = type
99
+ end
100
+ end
101
+
102
+ def set_table(name)
103
+ if @table
104
+ @table = "multiple" if @table != name
105
+ else
106
+ @table = name
107
+ end
108
+ end
109
+ end
110
+ end
@@ -0,0 +1,30 @@
1
+ require "rails/railtie"
2
+ require_relative "../active_record/trigger_helpers"
3
+
4
+ module PgTrigger
5
+ class Railtie < Rails::Railtie
6
+ initializer "pg_trigger.model" do
7
+ mod = if Rails.env.development? || Rails.env.test?
8
+ require "pg_trigger/model"
9
+ PgTrigger::Model
10
+ else
11
+ require "pg_trigger/noop"
12
+ PgTrigger::Noop
13
+ end
14
+
15
+ ActiveSupport.on_load :active_record do
16
+ self.include mod
17
+ end
18
+ end
19
+
20
+ initializer "pg_trigger.migration" do
21
+ ActiveSupport.on_load :active_record do
22
+ ::ActiveRecord::Migration.include(ActiveRecord::TriggerHelpers)
23
+ end
24
+ end
25
+
26
+ rake_tasks do
27
+ load "tasks/pg_trigger.rake"
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,61 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "strscan"
4
+
5
+ module PgTrigger
6
+ class Scanner
7
+ def initialize(str)
8
+ @str = str
9
+ @functions = {}
10
+ @definitions = []
11
+
12
+ parse
13
+ end
14
+
15
+ def triggers
16
+ @definitions.filter_map do |defn|
17
+ trigger = Trigger.from_definition(defn)
18
+ next nil unless trigger
19
+ next nil unless trigger.name.end_with?("_tr")
20
+
21
+ if (fn = @functions[trigger.name])
22
+ trigger.set_content_from_function(fn)
23
+ end
24
+
25
+ trigger
26
+ end
27
+ end
28
+
29
+ private
30
+
31
+ def parse
32
+ scanner = ::StringScanner.new(@str)
33
+ pos = 0
34
+
35
+ prefix = if (schema = PgTrigger.schema)
36
+ "#{schema}."
37
+ end
38
+
39
+ while true
40
+ break unless scanner.skip_until(/^CREATE FUNCTION /)
41
+ name = scanner.scan(/[\w\.]+_tr/)
42
+ next unless name
43
+
44
+ content = scanner.scan_until(/^\s*\$\$;/)
45
+ pos = scanner.pos
46
+
47
+ name.delete_prefix!(prefix) if prefix
48
+ @functions[name] = content
49
+ end
50
+
51
+ scanner.pos = pos
52
+ while true
53
+ break unless scanner.skip_until(/^CREATE TRIGGER/)
54
+ scanner.pos -= 14
55
+
56
+ defn = scanner.scan_until(/;/)
57
+ @definitions << defn
58
+ end
59
+ end
60
+ end
61
+ end
@@ -0,0 +1,190 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_support/core_ext/string/strip"
4
+ require_relative "indented_string"
5
+
6
+ module PgTrigger
7
+ class Trigger
8
+ class << self
9
+ def chain(*methods)
10
+ methods.each do |method|
11
+ class_eval <<-RUBY, __FILE__, __LINE__ + 1
12
+ alias orig_#{method} #{method}
13
+
14
+ def #{method}(*args, &block)
15
+ orig_#{method}(*args)
16
+ @content = normalize_string(yield) if block
17
+ self
18
+ end
19
+ RUBY
20
+ end
21
+ end
22
+
23
+ DEFN_REGEXP = [
24
+ "\\ACREATE TRIGGER",
25
+ "(?<name>\\w+)",
26
+ "(?<timing>AFTER|BEFORE)",
27
+ "(?<events>(?:INSERT|UPDATE|DELETE)(?: OR (?:INSERT|UPDATE|DELETE))?)",
28
+ "(?:OF(?<columns>(?:\\s[a-z0-9_]+,?)+)\\s)?ON (?:[\\w\"]+\\.)?(?<table>\\w+)",
29
+ "FOR EACH ROW(?: WHEN \\((?<where>[^\\)]+)\\))?",
30
+ "EXECUTE FUNCTION (?:\\w+\\.)?(?<fn>\\w+)",
31
+ ].join("\\s")
32
+ .yield_self { |str| Regexp.new(str) }
33
+
34
+ def from_definition(defn)
35
+ match = defn.match(DEFN_REGEXP)
36
+
37
+ if !match
38
+ raise InvalidTriggerDefinition, defn if PgTrigger.raise_on_invalid_definition
39
+ return
40
+ end
41
+
42
+ trigger = new
43
+ trigger.named(match[:name]).on(match[:table])
44
+ trigger.public_send(match[:timing].downcase, *match[:events].split(" OR ").map! { |e| e.downcase.to_sym })
45
+
46
+ if (cols = match[:columns])
47
+ trigger.of(*cols.split(", ").map!(&:lstrip))
48
+ end
49
+
50
+ if (where = match[:where])
51
+ trigger.where(where)
52
+ end
53
+
54
+ trigger.nowrap if match[:fn] != match[:name]
55
+ trigger
56
+ end
57
+ end
58
+
59
+ attr_reader :table, :timing, :content, :columns, :events
60
+
61
+ def initialize
62
+ @name = nil
63
+ @table = nil
64
+ @timing = nil
65
+ @events = []
66
+ @columns = []
67
+ @content = nil
68
+ @where = nil
69
+ @options = {}
70
+ end
71
+
72
+ def on(table_name)
73
+ @table = table_name
74
+ end
75
+
76
+ def after(*events)
77
+ @timing = :after
78
+ @events.concat(format_events(events))
79
+ end
80
+
81
+ def before(*events)
82
+ @timing = :before
83
+ @events.concat(format_events(events))
84
+ end
85
+
86
+ def of(*columns)
87
+ @columns.concat(columns)
88
+ end
89
+
90
+ def where(condition)
91
+ @where = condition
92
+ end
93
+
94
+ def named(name)
95
+ @name = name
96
+ end
97
+
98
+ def nowrap
99
+ @options[:nowrap] = true
100
+ end
101
+
102
+ chain :on, :of, :after, :before, :named, :where, :nowrap
103
+
104
+ def name
105
+ @name ||= inferred_name
106
+ end
107
+
108
+ def where_clause = @where
109
+
110
+ # Compare content without taking indentation into account
111
+ def same_content_as?(other)
112
+ content.gsub(/\s+/, " ") == other.content.gsub(/\s+/, " ")
113
+ end
114
+
115
+ FN_CONTENT_REGEX = /BEGIN\s+(?<content>.+;)\n\s+RETURN NULL;/m
116
+
117
+ def set_content_from_function(str)
118
+ if (match = str.match(FN_CONTENT_REGEX))
119
+ @content = match[:content]
120
+ end
121
+ end
122
+
123
+ def create_function?
124
+ !@options[:nowrap]
125
+ end
126
+
127
+ def create_function_sql
128
+ str = IndentedString.new(size: 4)
129
+ str += @content
130
+
131
+ <<~SQL
132
+ CREATE OR REPLACE FUNCTION #{name}() RETURNS TRIGGER
133
+ AS $$
134
+ BEGIN
135
+ #{str}
136
+ RETURN NULL;
137
+ END
138
+ $$ LANGUAGE plpgsql;
139
+ SQL
140
+ end
141
+
142
+ def create_trigger_sql
143
+ whr = @where.nil? ? "" : "\nWHEN (#@where)"
144
+
145
+ <<~SQL
146
+ CREATE TRIGGER #{name}
147
+ #{@timing.upcase} #{events.map(&:upcase).join(" OR ")} ON #{adapter.quote_table_name(@table)}
148
+ FOR EACH ROW#{whr}
149
+ EXECUTE FUNCTION #{name}();
150
+ SQL
151
+ end
152
+
153
+ def drop_function_sql
154
+ "DROP FUNCTION IF EXISTS #{name};"
155
+ end
156
+
157
+ def drop_trigger_sql
158
+ "DROP TRIGGER IF EXISTS #{name} ON #{adapter.quote_table_name(@table)};"
159
+ end
160
+
161
+ private
162
+
163
+ def format_events(ary)
164
+ ary.map do |e|
165
+ case e
166
+ when :insert, :update, :delete then e
167
+ when :create then :insert
168
+ when :destroy then :delete
169
+ else
170
+ raise ArgumentError, "unknown #{e}, event should be :insert, :update or :delete"
171
+ end
172
+ end
173
+ end
174
+
175
+ def normalize_string(str)
176
+ str.strip_heredoc.sub(/;?\s*\Z/, ";")
177
+ end
178
+
179
+ def adapter
180
+ @adapter ||= ::ActiveRecord::Base.connection
181
+ end
182
+
183
+ def inferred_name
184
+ [@table,
185
+ @timing,
186
+ @events.join("_or_"),
187
+ ].join("_").downcase.slice(0, 60) << "_tr"
188
+ end
189
+ end
190
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PgTrigger
4
+ VERSION = "0.1.0"
5
+ end
data/lib/pg_trigger.rb ADDED
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "pg_trigger/version"
4
+ require_relative "pg_trigger/railtie"
5
+
6
+ module PgTrigger
7
+ class InvalidTriggerDefinition < StandardError; end
8
+
9
+ class << self
10
+ attr_accessor :structure_file_path, :schema, :migrations_path, :raise_on_invalid_definition
11
+ end
12
+
13
+ self.structure_file_path = "db/structure.sql"
14
+ self.schema = "public"
15
+ self.migrations_path = "db/migrate"
16
+ self.raise_on_invalid_definition = false
17
+ end
@@ -0,0 +1 @@
1
+ require_relative "pg_trigger"
@@ -0,0 +1,22 @@
1
+ namespace :db do
2
+ namespace :triggers do
3
+ desc "Creates a new database migration representing changes in model-defined triggers"
4
+ task migration: :environment do
5
+ if ActiveRecord::Base.connection.migration_context.needs_migration?
6
+ puts "Abort: some migrations are pending"
7
+ exit(1)
8
+ end
9
+
10
+ require "pg_trigger/generator"
11
+
12
+ Rails.application.eager_load!
13
+ filename = PgTrigger::Generator.run(models: ActiveRecord::Base.descendants)
14
+
15
+ if filename
16
+ puts "Generated #{filename}"
17
+ else
18
+ puts "Everything up-to-date"
19
+ end
20
+ end
21
+ end
22
+ end
metadata ADDED
@@ -0,0 +1,120 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: rails-pg_trigger
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - ccocchi
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2024-01-15 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: activerecord
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '7.0'
20
+ - - "<"
21
+ - !ruby/object:Gem::Version
22
+ version: '8'
23
+ type: :runtime
24
+ prerelease: false
25
+ version_requirements: !ruby/object:Gem::Requirement
26
+ requirements:
27
+ - - ">="
28
+ - !ruby/object:Gem::Version
29
+ version: '7.0'
30
+ - - "<"
31
+ - !ruby/object:Gem::Version
32
+ version: '8'
33
+ - !ruby/object:Gem::Dependency
34
+ name: railties
35
+ requirement: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - ">="
38
+ - !ruby/object:Gem::Version
39
+ version: '7.0'
40
+ - - "<"
41
+ - !ruby/object:Gem::Version
42
+ version: '8'
43
+ type: :runtime
44
+ prerelease: false
45
+ version_requirements: !ruby/object:Gem::Requirement
46
+ requirements:
47
+ - - ">="
48
+ - !ruby/object:Gem::Version
49
+ version: '7.0'
50
+ - - "<"
51
+ - !ruby/object:Gem::Version
52
+ version: '8'
53
+ - !ruby/object:Gem::Dependency
54
+ name: pg
55
+ requirement: !ruby/object:Gem::Requirement
56
+ requirements:
57
+ - - '='
58
+ - !ruby/object:Gem::Version
59
+ version: 1.2.3
60
+ type: :runtime
61
+ prerelease: false
62
+ version_requirements: !ruby/object:Gem::Requirement
63
+ requirements:
64
+ - - '='
65
+ - !ruby/object:Gem::Version
66
+ version: 1.2.3
67
+ description: Write your Postgres triggers directly in your models.
68
+ email:
69
+ - cocchi.c@gmail.com
70
+ executables: []
71
+ extensions: []
72
+ extra_rdoc_files: []
73
+ files:
74
+ - ".standard.yml"
75
+ - CHANGELOG.md
76
+ - CODE_OF_CONDUCT.md
77
+ - Gemfile
78
+ - LICENSE.txt
79
+ - README.md
80
+ - Rakefile
81
+ - lib/active_record/trigger_helpers.rb
82
+ - lib/pg_trigger.rb
83
+ - lib/pg_trigger/generator.rb
84
+ - lib/pg_trigger/indented_string.rb
85
+ - lib/pg_trigger/model.rb
86
+ - lib/pg_trigger/noop.rb
87
+ - lib/pg_trigger/plan.rb
88
+ - lib/pg_trigger/railtie.rb
89
+ - lib/pg_trigger/scanner.rb
90
+ - lib/pg_trigger/trigger.rb
91
+ - lib/pg_trigger/version.rb
92
+ - lib/rails-pg_trigger.rb
93
+ - lib/tasks/pg_trigger.rake
94
+ homepage: https://github.com/ccocchi/rails-pg_trigger
95
+ licenses:
96
+ - MIT
97
+ metadata:
98
+ homepage_uri: https://github.com/ccocchi/rails-pg_trigger
99
+ source_code_uri: https://github.com/ccocchi/rails-pg_trigger
100
+ changelog_uri: https://github.com/ccocchi/rails-pg_trigger/blob/main/CHANGELOG.md
101
+ post_install_message:
102
+ rdoc_options: []
103
+ require_paths:
104
+ - lib
105
+ required_ruby_version: !ruby/object:Gem::Requirement
106
+ requirements:
107
+ - - ">="
108
+ - !ruby/object:Gem::Version
109
+ version: 3.1.2
110
+ required_rubygems_version: !ruby/object:Gem::Requirement
111
+ requirements:
112
+ - - ">="
113
+ - !ruby/object:Gem::Version
114
+ version: '0'
115
+ requirements: []
116
+ rubygems_version: 3.3.7
117
+ signing_key:
118
+ specification_version: 4
119
+ summary: Postgres triggers for Rails
120
+ test_files: []