pg_advisory_lock 0.1.0

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.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 9ddeeb1356cb650c405bbd16569ac2e2c8d7cfb3e3c4315af9f55aee4a5594bd
4
+ data.tar.gz: becf789c25d232dccb5ce1504f5bd6aeef9d1b491e9f6ab85a4d9b42ae5e5c77
5
+ SHA512:
6
+ metadata.gz: 4e7ee3ae26d4c4413e13fad975c5dcd2adbdefc0a2b3c6b70a9b94fcffe44c4ec466b7655752dc0f98dab3951a1f2841314763d6e42ca0672a85c1b720837530
7
+ data.tar.gz: 9c865edbfdafd873c29e83cd731e438a3d7b504872a3853e6c724549cfeee8f79804d157271b5bc4b06cc568c45f3f5e3f94df5c79df5e036fbd04303cf9a0d0
@@ -0,0 +1,14 @@
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
12
+
13
+ /Gemfile.lock
14
+ /spec/config/database.yml
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
@@ -0,0 +1,71 @@
1
+ AllCops:
2
+ DisplayCopNames: true
3
+ TargetRubyVersion: 2.5
4
+ Exclude:
5
+ - vendor/**/*
6
+ - tmp/**/*
7
+
8
+ Layout/LineLength:
9
+ Max: 180
10
+
11
+ Style/SymbolArray:
12
+ EnforcedStyle: brackets
13
+
14
+ Style/Lambda:
15
+ EnforcedStyle: literal
16
+
17
+ Naming/MethodParameterName:
18
+ AllowedNames:
19
+ - id
20
+
21
+ Style/HashEachMethods:
22
+ Enabled: true
23
+
24
+ Style/HashTransformKeys:
25
+ Enabled: true
26
+
27
+ Style/HashTransformValues:
28
+ Enabled: true
29
+
30
+ Style/Documentation:
31
+ Enabled: false
32
+
33
+ Metrics/PerceivedComplexity:
34
+ Enabled: false
35
+
36
+ Metrics/MethodLength:
37
+ Enabled: false
38
+
39
+ Metrics/AbcSize:
40
+ Enabled: false
41
+
42
+ Metrics/ModuleLength:
43
+ Enabled: false
44
+
45
+ Metrics/BlockLength:
46
+ Enabled: false
47
+
48
+ Metrics/ClassLength:
49
+ Enabled: false
50
+
51
+ Metrics/CyclomaticComplexity:
52
+ Enabled: false
53
+
54
+ Layout/MultilineOperationIndentation:
55
+ Enabled: false
56
+
57
+ Layout/FirstHashElementIndentation:
58
+ Enabled: false
59
+
60
+ Layout/FirstArrayElementIndentation:
61
+ Enabled: false
62
+
63
+ Layout/FirstArgumentIndentation:
64
+ Enabled: false
65
+
66
+ Layout/ClosingParenthesisIndentation:
67
+ Enabled: false
68
+
69
+ Layout/ArgumentAlignment:
70
+ Enabled: false
71
+
@@ -0,0 +1,6 @@
1
+ ---
2
+ language: ruby
3
+ cache: bundler
4
+ rvm:
5
+ - 2.5.5
6
+ before_install: gem install bundler -v 2.1.4
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at senid231@gmail.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [https://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: https://contributor-covenant.org
74
+ [version]: https://contributor-covenant.org/version/1/4/
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 pg_advisory_lock.gemspec
6
+ gemspec
7
+
8
+ gem 'database_cleaner'
9
+ gem 'pg'
10
+ gem 'rake', '~> 12.0'
11
+ gem 'rspec', '~> 3.0'
12
+ gem 'rubocop', '~> 0.80.1'
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2020 Denis Talakevich
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,66 @@
1
+ # PgAdvisoryLock
2
+
3
+ Postgresql Advisory Lock for ActiveRecord.
4
+ Allows to use mutex in applications that uses same database.
5
+
6
+ ## Installation
7
+
8
+ Add this line to your application's Gemfile:
9
+
10
+ ```ruby
11
+ gem 'pg_advisory_lock'
12
+ ```
13
+
14
+ And then execute:
15
+
16
+ $ bundle install
17
+
18
+ Or install it yourself as:
19
+
20
+ $ gem install pg_advisory_lock
21
+
22
+ ## Usage
23
+
24
+ create subclass from `PgAdvisoryLock::Base` and define `model_class` for it
25
+
26
+ ```ruby
27
+ require 'pg_sql_caller'
28
+
29
+ class MySqlCaller < PgAdvisoryLock::Base
30
+ model_class 'ApplicationRecord'
31
+ end
32
+
33
+ MySqlCaller.select_values 'SELECT id from users WHERE parent_name = ?', 'John Doe' # => [1, 2, 3]
34
+ ```
35
+
36
+ or just define `model_class` for `PgAdvisoryLock::Base` itself
37
+
38
+ ```ruby
39
+ PgAdvisoryLock::Base.model_class 'ApplicationRecord'
40
+
41
+ PgAdvisoryLock::Base.select_values 'SELECT id from users WHERE parent_name = ?', 'John Doe' # => [1, 2, 3]
42
+ ```
43
+
44
+ ## Development
45
+
46
+ After checking out the repo, run `bin/setup` to install dependencies.
47
+ Create `spec/config/database.yml` (look at `spec/config/database.travis.yml` for example).
48
+ You need to create test database, so run `psql -c 'CREATE DATABASE pg_advisory_lock_test;'`.
49
+ Then, run `rake spec` to run the tests.
50
+ You can also run `bin/console` for an interactive prompt that will allow you to experiment.
51
+
52
+ To install this gem onto your local machine, run `bundle exec rake install`.
53
+ 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).
54
+
55
+ ## Contributing
56
+
57
+ Bug reports and pull requests are welcome on GitHub at https://github.com/senid231/pg_advisory_lock. 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/senid231/pg_advisory_lock/blob/master/CODE_OF_CONDUCT.md).
58
+
59
+
60
+ ## License
61
+
62
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
63
+
64
+ ## Code of Conduct
65
+
66
+ Everyone interacting in the PgAdvisoryLock project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/senid231/pg_advisory_lock/blob/master/CODE_OF_CONDUCT.md).
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rspec/core/rake_task'
5
+ require 'rubocop/rake_task'
6
+
7
+ RSpec::Core::RakeTask.new(:spec)
8
+ RuboCop::RakeTask.new(:rubocop)
9
+
10
+ task default: [:rubocop, :spec]
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require 'bundler/setup'
5
+ require 'pg_advisory_lock'
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ # (If you use this, don't forget to add pry to your Gemfile!)
11
+ # require "pry"
12
+ # Pry.start
13
+
14
+ require 'irb'
15
+ IRB.start(__FILE__)
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'pg_advisory_lock/version'
4
+ require 'pg_advisory_lock/base'
5
+
6
+ module PgAdvisoryLock
7
+ # Your code goes here...
8
+ end
@@ -0,0 +1,133 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'active_support/logger'
4
+ require 'pg_sql_caller'
5
+
6
+ module PgAdvisoryLock
7
+ class Base
8
+ # Encapsulates advisory lock logic.
9
+ # https://www.postgresql.org/docs/9.3/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS-TABLE
10
+ # Allows to use mutex in applications that uses same database.
11
+
12
+ class_attribute :logger, instance_writer: false, default: ActiveSupport::Logger.new(STDOUT)
13
+ class_attribute :_sql_caller_class, instance_writer: false, default: PgSqlCaller::Base
14
+ class_attribute :_lock_names, instance_writer: false, default: {}
15
+
16
+ class << self
17
+ def inherited(subclass)
18
+ subclass._lock_names = {}
19
+ super
20
+ end
21
+
22
+ # @param name [Symbol, String]
23
+ # @param value [Integer, Array<(Integer, Integer)>]
24
+ def register_lock(name, value)
25
+ _lock_names[name.to_sym] = value
26
+ end
27
+
28
+ # @param klass [Class<PgSqlCaller::Base>, String]
29
+ def sql_caller_class(klass)
30
+ self._sql_caller_class = klass
31
+ end
32
+
33
+ # @param name [Symbol, String] - lock name (will be transformed to number).
34
+ # @param transaction [Boolean] - if true lock will be released at the end of current transaction
35
+ # otherwise it will be released at the end of block.
36
+ # @param shared [Boolean] - is lock shared or not.
37
+ # @param id [Integer] - number that will be used in pair with lock number to perform advisory lock.
38
+ # @yield - call block when lock is acquired
39
+ # block must be passed if transaction argument is false.
40
+ # @raise [ArgumentError] when lock name is invalid.
41
+ # @return yield
42
+ def with_lock(name, transaction: false, shared: false, id: nil, &block)
43
+ new(name, transaction: transaction, shared: shared, id: id).lock(&block)
44
+ end
45
+ end
46
+
47
+ # @param name [Symbol, String] - lock name (will be transformed to number).
48
+ # @param transaction [Boolean] - if true lock will be released at the end of current transaction
49
+ # otherwise it will be released at the end of block.
50
+ # @param shared [Boolean] - is lock shared or not.
51
+ # @param id [Integer] - number that will be used in pair with lock number to perform advisory lock.
52
+ def initialize(name, transaction: false, shared: false, id: nil)
53
+ @name = name.to_sym
54
+ @transaction = transaction
55
+ @shared = shared
56
+ @id = id
57
+ end
58
+
59
+ # @yield - call block when lock is acquired
60
+ # block must be passed if transaction argument is false.
61
+ # @raise [ArgumentError] when lock name is invalid.
62
+ # @return yield
63
+ def lock(&block)
64
+ with_logger do
65
+ lock_number = name_to_number
66
+ advisory_lock(lock_number, &block)
67
+ end
68
+ end
69
+
70
+ private
71
+
72
+ attr_reader :transaction, :shared, :name, :id
73
+
74
+ def with_logger
75
+ return yield if logger.nil? || !logger.respond_to?(:tagged)
76
+
77
+ logger.tagged(self.class.to_s, name.inspect) { yield }
78
+ end
79
+
80
+ def advisory_lock(lock_number, &block)
81
+ if transaction
82
+ transaction_lock(lock_number, &block)
83
+ else
84
+ non_transaction_lock(lock_number, &block)
85
+ end
86
+ end
87
+
88
+ def transaction_lock(lock_number)
89
+ raise ArgumentError, 'block required when not within transaction' if !block_given? && !_sql_caller_class.transaction_open?
90
+
91
+ return perform_lock(lock_number) unless block_given?
92
+
93
+ _sql_caller_class.transaction do
94
+ perform_lock(lock_number)
95
+ yield
96
+ end
97
+ end
98
+
99
+ def non_transaction_lock(lock_number)
100
+ raise ArgumentError, 'block required on transaction: false' unless block_given?
101
+
102
+ begin
103
+ perform_lock(lock_number)
104
+ yield
105
+ ensure
106
+ perform_unlock(lock_number)
107
+ end
108
+ end
109
+
110
+ def perform_lock(lock_number)
111
+ function_name = "pg_advisory#{'_xact' if transaction}_lock#{'_shared' if shared}"
112
+
113
+ _sql_caller_class.execute("SELECT #{function_name}(#{lock_number})")
114
+ end
115
+
116
+ def perform_unlock(lock_number)
117
+ _sql_caller_class.select_value("SELECT pg_advisory_unlock#{'_shared' if shared}(#{lock_number})")
118
+ end
119
+
120
+ # Converts lock name to number, because pg advisory lock functions accept only bigint numbers.
121
+ # @return [String] lock number or two numbers delimited by comma.
122
+ def name_to_number
123
+ lock_number = _lock_names.fetch(name) do
124
+ raise ArgumentError, "lock name #{name.inspect} is invalid, see #{self.class}::NAMES"
125
+ end
126
+ lock_number = Array.wrap(lock_number)
127
+ lock_number.push(id) if id.present?
128
+ raise ArgumentError, "can't use lock name #{name.inspect} with id" if lock_number.size > 2
129
+
130
+ lock_number.join(', ')
131
+ end
132
+ end
133
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PgAdvisoryLock
4
+ VERSION = '0.1.0'
5
+ end
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'lib/pg_advisory_lock/version'
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = 'pg_advisory_lock'
7
+ spec.version = PgAdvisoryLock::VERSION
8
+ spec.authors = ['Denis Talakevich']
9
+ spec.email = ['senid231@gmail.com']
10
+
11
+ spec.summary = 'Postgresql Advisory Lock for ActiveRecord'
12
+ spec.description = 'Postgresql Advisory Lock for ActiveRecord.'
13
+ spec.homepage = 'https://github.com/senid231/pg_advisory_lock'
14
+ spec.license = 'MIT'
15
+ spec.required_ruby_version = Gem::Requirement.new('>= 2.3.0')
16
+
17
+ spec.metadata['homepage_uri'] = spec.homepage
18
+ spec.metadata['source_code_uri'] = spec.homepage
19
+ spec.metadata['changelog_uri'] = spec.homepage
20
+
21
+ # Specify which files should be added to the gem when it is released.
22
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
23
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
24
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
25
+ end
26
+ spec.bindir = 'exe'
27
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
28
+ spec.require_paths = ['lib']
29
+
30
+ spec.add_dependency 'activerecord'
31
+ spec.add_dependency 'activesupport'
32
+ spec.add_dependency 'pg_sql_caller'
33
+ end
metadata ADDED
@@ -0,0 +1,103 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: pg_advisory_lock
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Denis Talakevich
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2020-03-24 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: '0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: activesupport
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: pg_sql_caller
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ description: Postgresql Advisory Lock for ActiveRecord.
56
+ email:
57
+ - senid231@gmail.com
58
+ executables: []
59
+ extensions: []
60
+ extra_rdoc_files: []
61
+ files:
62
+ - ".gitignore"
63
+ - ".rspec"
64
+ - ".rubocop.yml"
65
+ - ".travis.yml"
66
+ - CODE_OF_CONDUCT.md
67
+ - Gemfile
68
+ - LICENSE.txt
69
+ - README.md
70
+ - Rakefile
71
+ - bin/console
72
+ - bin/setup
73
+ - lib/pg_advisory_lock.rb
74
+ - lib/pg_advisory_lock/base.rb
75
+ - lib/pg_advisory_lock/version.rb
76
+ - pg_advisory_lock.gemspec
77
+ homepage: https://github.com/senid231/pg_advisory_lock
78
+ licenses:
79
+ - MIT
80
+ metadata:
81
+ homepage_uri: https://github.com/senid231/pg_advisory_lock
82
+ source_code_uri: https://github.com/senid231/pg_advisory_lock
83
+ changelog_uri: https://github.com/senid231/pg_advisory_lock
84
+ post_install_message:
85
+ rdoc_options: []
86
+ require_paths:
87
+ - lib
88
+ required_ruby_version: !ruby/object:Gem::Requirement
89
+ requirements:
90
+ - - ">="
91
+ - !ruby/object:Gem::Version
92
+ version: 2.3.0
93
+ required_rubygems_version: !ruby/object:Gem::Requirement
94
+ requirements:
95
+ - - ">="
96
+ - !ruby/object:Gem::Version
97
+ version: '0'
98
+ requirements: []
99
+ rubygems_version: 3.0.4
100
+ signing_key:
101
+ specification_version: 4
102
+ summary: Postgresql Advisory Lock for ActiveRecord
103
+ test_files: []