dynamodb-ruby 0.2.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: d56caaa4e174f830bfa8e20151e848457ae6154e
4
+ data.tar.gz: 95177ad6f13526ba23c2587a72994ef2d6d0da0c
5
+ SHA512:
6
+ metadata.gz: adbfd0dcdc70eb9fac17dece03d3591dfb5103f4b17a3de3c84a2611770b8b2d3c28ded95bea214feb328f421d7536bdf7471ca9cf12f047babdbdf830f00d11
7
+ data.tar.gz: b8e9258db501e9d5b6c0b42bc5f1b0da3b7c29086808ac2d220fe16a6e1d9cb80963b95b3cb29ee7703aebd03c54b1fa1afafef619796a6d76080175cfde852c
@@ -0,0 +1,12 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
10
+
11
+ # rspec failure tracking
12
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --format documentation
2
+ --color
@@ -0,0 +1,5 @@
1
+ sudo: false
2
+ language: ruby
3
+ rvm:
4
+ - 2.3.1
5
+ before_install: gem install bundler -v 1.15.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 sfarrow@bandsintown.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 [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ source "https://rubygems.org"
2
+
3
+ git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
4
+
5
+ # Specify your gem's dependencies in dynamodb-ruby.gemspec
6
+ gemspec
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2017 Steve Farrow
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,43 @@
1
+ # Dynamodb
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/dynamodb`. 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
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'dynamodb-ruby'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install dynamodb-ruby
22
+
23
+ ## Usage
24
+
25
+ TODO: Write usage instructions here
26
+
27
+ ## Development
28
+
29
+ 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.
30
+
31
+ 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).
32
+
33
+ ## Contributing
34
+
35
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/dynamodb-ruby. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
36
+
37
+ ## License
38
+
39
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
40
+
41
+ ## Code of Conduct
42
+
43
+ Everyone interacting in the Dynamodb project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/dynamodb-ruby/blob/master/CODE_OF_CONDUCT.md).
@@ -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,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "dynamodb"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ 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
Binary file
@@ -0,0 +1,40 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path("../lib", __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require "dynamodb/version"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "dynamodb-ruby"
8
+ spec.version = Dynamodb::VERSION
9
+ spec.authors = ["Steve Farrow"]
10
+ spec.email = ["sfarrow@bandsintown.com"]
11
+
12
+ spec.summary = %q{A small ORM wrapper to make working with AWS Dynamodb easier.}
13
+ spec.description = %q{A small ORM wrapper to make working with AWS Dynamodb easier. Includes Test helpers.}
14
+ spec.homepage = "https://www.bandsintown.com"
15
+ spec.license = "MIT"
16
+
17
+ # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
18
+ # to allow pushing to a single host or delete this section to allow pushing to any host.
19
+ # if spec.respond_to?(:metadata)
20
+ # spec.metadata["allowed_push_host"] = "TODO: Set to 'http://mygemserver.com'"
21
+ # else
22
+ # raise "RubyGems 2.0 or newer is required to protect against " \
23
+ # "public gem pushes."
24
+ # end
25
+
26
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
27
+ f.match(%r{^(test|spec|features)/})
28
+ end
29
+ spec.bindir = "exe"
30
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
31
+ spec.require_paths = ["lib"]
32
+
33
+ spec.add_dependency "activesupport", "~> 5.0"
34
+ spec.add_dependency "aws-sdk-dynamodb", "~> 1"
35
+
36
+ spec.add_development_dependency "bundler", "~> 1.15"
37
+ spec.add_development_dependency "rake", "~> 10.0"
38
+ spec.add_development_dependency "rspec", "~> 3.2"
39
+ spec.add_development_dependency "pry"
40
+ end
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "dynamodb/version"
4
+ require "dynamodb/connection"
5
+ require "dynamodb/table_actions"
6
+
7
+ module Dynamodb
8
+ extend Connection
9
+ extend TableActions
10
+ end
@@ -0,0 +1,165 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Dynamodb
4
+ module AttributeAssignment
5
+ def self.included(base)
6
+ base.extend ClassMethods
7
+ end
8
+
9
+ ATTRIBUTE_TYPES = {
10
+ string: "S",
11
+ number: "N",
12
+ binary: "B"
13
+ }
14
+
15
+ KEY_TYPES = {
16
+ hash: "HASH",
17
+ range: "RANGE"
18
+ }
19
+
20
+ PROJECTION_TYPES = {
21
+ all: "ALL",
22
+ keys: "KEYS_ONLY",
23
+ include: "INCLUDE"
24
+ }
25
+
26
+ def table_name
27
+ self.class.table_name
28
+ end
29
+
30
+ def hash_key
31
+ self.class.hash_key
32
+ end
33
+
34
+ def range_key
35
+ self.class.range_key
36
+ end
37
+
38
+ def client
39
+ self.class.client
40
+ end
41
+
42
+ def indexes
43
+ self.class.indexes
44
+ end
45
+
46
+ def local_indexes
47
+ self.class.local_indexes
48
+ end
49
+
50
+ def global_indexes
51
+ self.class.global_indexes
52
+ end
53
+
54
+ module ClassMethods
55
+ attr_reader :hash_key, :range_key, :attribute_definitions,
56
+ :key_schema, :indexes, :local_indexes, :global_indexes
57
+
58
+ def table_name(_table_name = nil)
59
+ return (@_table_name || name.tableize) if _table_name.nil?
60
+
61
+ @_table_name = _table_name.to_s
62
+ end
63
+
64
+ def local_indexes
65
+ indexes_for(:local)
66
+ end
67
+
68
+ def global_indexes
69
+ indexes_for(:global)
70
+ end
71
+
72
+ def key(attr_name, attr_type, options)
73
+ instance_variable_set("@#{options[:key]}_key", attr_name.to_s)
74
+ define_attribute({ name: attr_name, type: attr_type })
75
+ define_key_schema(attr_name, options[:key])
76
+ end
77
+
78
+ def local_index(options)
79
+ @indexes ||= []
80
+ @indexes << define_local_index(options)
81
+ define_attribute(
82
+ {
83
+ name: options[:key][:name],
84
+ type: options[:key][:type]
85
+ }
86
+ )
87
+ end
88
+
89
+ def global_index(options)
90
+ @indexes ||= []
91
+ @indexes << define_global_index(options)
92
+ options[:keys].keys.each do |_key|
93
+ define_attribute(
94
+ {
95
+ name: options[:keys][_key][:name],
96
+ type: options[:keys][_key][:type]
97
+ }
98
+ )
99
+ end
100
+ end
101
+
102
+ def time_to_live(&block)
103
+ define_method :schedule_time_to_live, &block
104
+ end
105
+
106
+ private
107
+
108
+ def define_attribute(name:, type:)
109
+ @attribute_definitions ||= []
110
+ attr_def = { attribute_name: name.to_s, attribute_type: ATTRIBUTE_TYPES[type] }
111
+ @attribute_definitions << attr_def unless @attribute_definitions.include?(attr_def)
112
+ end
113
+
114
+ def define_key_schema(attr_name, key_type)
115
+ @key_schema ||= []
116
+ @key_schema << { attribute_name: attr_name.to_s, key_type: KEY_TYPES[key_type] }
117
+ end
118
+
119
+ def define_local_index(options)
120
+ hash_key_schema =
121
+ @key_schema.detect { |k| k[:attribute_name] == @hash_key }
122
+
123
+ {
124
+ type: :local,
125
+ index_name: options[:name].to_s,
126
+ key_schema: [
127
+ hash_key_schema,
128
+ { attribute_name: options[:key][:name].to_s, key_type: KEY_TYPES[:range] }
129
+ ],
130
+ projection: define_projection(options)
131
+ }
132
+ end
133
+
134
+ def define_global_index(options)
135
+ {
136
+ type: :global,
137
+ index_name: options[:name].to_s,
138
+ key_schema: options[:keys].keys.each_with_object([]) do |_key, obj|
139
+ obj << { attribute_name: options[:keys][_key][:name].to_s, key_type: KEY_TYPES[_key] }
140
+ end,
141
+ projection: define_projection(options)
142
+ }
143
+ end
144
+
145
+ def define_projection(options)
146
+ p_hash = {
147
+ projection_type: PROJECTION_TYPES[options[:projection]]
148
+ }
149
+
150
+ p_hash.merge!({
151
+ non_key_attributes: options[:attributes]
152
+ }) if options[:projection] == :include
153
+
154
+ p_hash
155
+ end
156
+
157
+ def indexes_for(type)
158
+ return if @indexes.nil?
159
+
160
+ @indexes.select { |h| h[:type] == type }
161
+ .map { |h| h.select { |k| k != :type }}
162
+ end
163
+ end
164
+ end
165
+ end
@@ -0,0 +1,91 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "dynamodb/connection"
4
+ require "dynamodb/attribute_assignment"
5
+ require "dynamodb/querying"
6
+ require "active_support/core_ext/hash/keys"
7
+ require "active_support/core_ext/hash/indifferent_access"
8
+ require "active_support/core_ext/string/inflections"
9
+
10
+ ##
11
+ # Represents a data hash object that is can be stored in a DynamoDB
12
+ # NoSql Database.
13
+ module Dynamodb
14
+ class Base
15
+ extend Connection
16
+ include AttributeAssignment
17
+ include Querying
18
+
19
+ attr_accessor :data
20
+ attr_reader :errors
21
+
22
+ def initialize(data = {}, new_record = true)
23
+ self.data = data
24
+ @new_record = new_record
25
+ @errors = []
26
+ end
27
+
28
+ def data=(val)
29
+ @data = val.deep_stringify_keys
30
+ end
31
+
32
+ def data
33
+ normalize_hash_key # otherwise returns a BigDecimal
34
+ @data.with_indifferent_access
35
+ end
36
+
37
+ def new_record?
38
+ @new_record.nil? ? false : @new_record
39
+ end
40
+
41
+ def valid?
42
+ # Checks to make sure the data is in the proper format and includes the
43
+ # hash_key Primary Key, and range_key if has one
44
+ # TODO need to validate data is a hash earlier
45
+ # @data = 'a string'
46
+ @errors = [] # start fresh
47
+ return true if valid_data_format? && valid_hash_key? && valid_range_key?
48
+
49
+ @errors << "Incorrect format of data"
50
+ false # is not valid
51
+ end
52
+
53
+ def handle_error(e)
54
+ @errors << e.message
55
+ end
56
+
57
+ def add_error(e)
58
+ @errors << e
59
+ end
60
+
61
+ def generate_timestamps
62
+ self&.schedule_time_to_live
63
+ @data["updated_at"] = Time.now.utc.iso8601
64
+ @data["created_at"] = Time.now.utc.iso8601 if new_record?
65
+ end
66
+
67
+ private
68
+
69
+ def normalize_hash_key
70
+ return unless @data[hash_key].is_a? BigDecimal
71
+ @data[hash_key] = @data[hash_key].to_i
72
+ end
73
+
74
+ def valid_data_format?
75
+ data.is_a? Hash
76
+ end
77
+
78
+ def valid_hash_key?
79
+ data.key?(hash_key)
80
+ end
81
+
82
+ def valid_range_key?
83
+ return true if range_key.nil?
84
+ data.key?(range_key)
85
+ end
86
+
87
+ def self.not_found
88
+ { error: "Not Found" }
89
+ end
90
+ end
91
+ end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "aws-sdk-dynamodb"
4
+
5
+ module Dynamodb
6
+ module Connection
7
+ def client
8
+ @@client ||= Aws::DynamoDB::Client.new(config)
9
+ end
10
+
11
+ def client=(new_connection)
12
+ @@client = new_connection
13
+ end
14
+
15
+ def reset_client
16
+ @@client = nil
17
+ @@resource = nil
18
+ end
19
+
20
+ def resource
21
+ @@resource ||= Aws::DynamoDB::Resource.new(client: client)
22
+ end
23
+
24
+ def resource=(new_resource)
25
+ @@resource = new_resource
26
+ end
27
+
28
+ def config
29
+ @@config ||= { endpoint: "http://localhost:10070" }
30
+ end
31
+
32
+ def config=(client_config)
33
+ @@config = client_config
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,89 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "dynamodb"
4
+ require "dynamodb_schema"
5
+
6
+ module Dynamodb
7
+ class Local
8
+ extend DynamoDBSchema
9
+
10
+ class << self
11
+ attr_reader :dynamodb
12
+
13
+ def init_dynamodb
14
+ @dynamodb ||= Dynamodb
15
+ # Note: Set database to point to dynamodb local
16
+ @dynamodb.config = { endpoint: "http://localhost:10070" }
17
+ @dynamodb.reset_client # reset the connection
18
+ end
19
+
20
+ def reset
21
+ init_dynamodb
22
+
23
+ teardown
24
+ build_tables # DynamoDBSchema#build_tables
25
+ rescue => e
26
+ splat_error("Unable to reset DynamoDB:", e.message)
27
+ end
28
+
29
+ def teardown
30
+ @dynamodb.list_tables.each do |table|
31
+ @dynamodb.delete_table(table)
32
+ end
33
+ rescue => e
34
+ splat_error("Unable to teardown DynamoDB tables:", e.message)
35
+ end
36
+
37
+ def create_table(table_name, klass, &block)
38
+ params = build_table_attrs(klass)
39
+ params.merge!(yield) if block_given? # merge overrides
40
+ @dynamodb.create_table(table_name, params)
41
+ rescue Aws::DynamoDB::Errors => e
42
+ splat_error("Unable to create DynamoDB tables:", e.message)
43
+ end
44
+
45
+ def build_table_attrs(klass)
46
+ params =
47
+ {
48
+ attribute_definitions: klass.attribute_definitions,
49
+ key_schema: klass.key_schema,
50
+ provisioned_throughput: provisioned_throughput
51
+ }
52
+
53
+ params.merge!(
54
+ local_secondary_indexes: klass.local_indexes
55
+ ) unless klass.local_indexes.empty?
56
+
57
+ unless klass.global_indexes.empty?
58
+ global_indexes_hash = klass.global_indexes.map do |x|
59
+ x.merge({ provisioned_throughput: provisioned_throughput })
60
+ end
61
+ params.merge!(
62
+ global_secondary_indexes: global_indexes_hash
63
+ )
64
+ end
65
+
66
+ params
67
+ end
68
+
69
+ def provisioned_throughput
70
+ {
71
+ read_capacity_units: 10,
72
+ write_capacity_units: 10
73
+ }
74
+ end
75
+
76
+ def splat_error(title, message)
77
+ puts <<-HEREDOC
78
+ ##############################
79
+
80
+ #{title}
81
+
82
+ #{message}
83
+
84
+ ##############################
85
+ HEREDOC
86
+ end
87
+ end
88
+ end
89
+ end
@@ -0,0 +1,91 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "dynamodb/relation"
4
+ require "dynamodb/table_actions"
5
+
6
+ module Dynamodb
7
+ module Querying
8
+ extend TableActions
9
+
10
+ def self.included(base)
11
+ base.extend ClassMethods
12
+ base.extend TableActions
13
+ end
14
+
15
+ def update(attributes = {})
16
+ # Stringify keys for updated attributes - data consistency
17
+ @data.deep_merge!(attributes.deep_stringify_keys)
18
+
19
+ return false unless valid?
20
+
21
+ generate_timestamps
22
+ self.class.put_item(table_name, @data)
23
+ true
24
+ rescue Aws::DynamoDB::Errors::ServiceError => e
25
+ handle_error(e)
26
+ false
27
+ end
28
+
29
+ def save
30
+ return false unless valid?
31
+
32
+ generate_timestamps
33
+ self.class.put_item(table_name, @data)
34
+ true
35
+ rescue Aws::DynamoDB::Errors::ServiceError => e
36
+ handle_error(e)
37
+ false
38
+ end
39
+
40
+ def destroy
41
+ _keys = self.class._key_definitions(@data[hash_key], @data[range_key])
42
+ self.class.delete_item(table_name, _keys)
43
+ true
44
+ rescue Aws::DynamoDB::Errors::ServiceError => e
45
+ handle_error(e)
46
+ false
47
+ end
48
+
49
+ module ClassMethods
50
+ def find(h_key, r_key = nil)
51
+ get_item(table_name, _key_definitions(h_key, r_key)) || not_found
52
+ rescue Aws::DynamoDB::Errors::ServiceError => e
53
+ not_found
54
+ end
55
+
56
+ def find_or_initialize_by(h_key, r_key = nil)
57
+ response = find(h_key, r_key)
58
+ response.is_a?(Hash) ? new(_key_definitions(h_key, r_key)) : response
59
+ end
60
+
61
+ def create(data = {}, conditions = {})
62
+ object = new(data)
63
+
64
+ return object unless object.valid?
65
+ # TODO: Need to test conditions - condition_expressions
66
+ object.generate_timestamps
67
+ put_item(table_name, object.data, conditions)
68
+
69
+ object
70
+ rescue Aws::DynamoDB::Errors::ServiceError => e
71
+ object.handle_error(e)
72
+ object
73
+ end
74
+
75
+ # Build up a chain in response to a method
76
+ # TODO: Need to write tests
77
+ [:where, :limit, :select, :all, :query, :to_query].each do |meth|
78
+ define_method(meth) do |*args|
79
+ chain = Dynamodb::Relation.new(self)
80
+ args ? chain.send(meth, *args) : chain.send(meth)
81
+ end
82
+ end
83
+
84
+ def _key_definitions(h_value, r_value = nil)
85
+ attrs = { hash_key => h_value }
86
+ attrs.merge!({ range_key => r_value }) if r_value
87
+ attrs
88
+ end
89
+ end
90
+ end
91
+ end
@@ -0,0 +1,197 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Builds a Query for the DynamoDB table.
4
+ #
5
+ # @param [Object] source DynamoDB table object
6
+
7
+ module Dynamodb
8
+ class Relation
9
+ attr_accessor :source, :consistent_read, :scan_index_forward
10
+ attr_reader :index_name, :key_condition_expression, :filter_expression,
11
+ :expression_attribute_names, :expression_attribute_values,
12
+ :filter_expression, :projection_expression,
13
+ :attribute_expressors, :offset_key
14
+
15
+ OPERATOR_MAP = {
16
+ eq: "=",
17
+ gt: ">",
18
+ gte: ">=",
19
+ lt: "<",
20
+ lte: "<=",
21
+ begins_with: "begins_with",
22
+ between: "BETWEEN"
23
+ }.freeze
24
+
25
+ QUERY_METHODS = [
26
+ :index_name, :consistent_read, :scan_index_forward,
27
+ :key_condition_expression, :filter_expression, :expression_attribute_names,
28
+ :expression_attribute_values, :projection_expression, :exclusive_start_key
29
+ ].freeze
30
+
31
+ QUERY_INSTANCE_VARS = [
32
+ :limit
33
+ ].freeze
34
+
35
+ def initialize(source)
36
+ @source = source
37
+ @attribute_expressors = {}
38
+ @consistent_read = false
39
+ @scan_index_forward = true
40
+ end
41
+
42
+ def where(args)
43
+ args.each do |k, v|
44
+ setter = "#{k}=".to_sym
45
+ self.has_method?(setter) ? self.send(setter, v) : add_attribute_query(k,v)
46
+ end
47
+ build_expressions
48
+ self
49
+ end
50
+
51
+ def limit(int)
52
+ @_limit = int
53
+ build_expressions
54
+ self
55
+ end
56
+
57
+ def select(*args)
58
+ @projection_expression = args.flatten
59
+ build_expressions
60
+ self
61
+ end
62
+
63
+ def all
64
+ source._query(build_query)
65
+ end
66
+
67
+ def to_query
68
+ build_query
69
+ end
70
+
71
+ def query(args = {})
72
+ source._query(args)
73
+ end
74
+
75
+ def key_condition_expression
76
+ @key_condition_expression.join(" AND ")
77
+ end
78
+
79
+ def filter_expression
80
+ @filter_expression.join(" AND ")
81
+ end
82
+
83
+ def projection_expression
84
+ return nil if @projection_expression.nil?
85
+
86
+ @projection_expression.join(", ")
87
+ end
88
+
89
+ def exclusive_start_key
90
+ @offset_key
91
+ end
92
+
93
+ protected
94
+
95
+ def has_method?(meth)
96
+ self.class.private_method_defined?(meth)
97
+ end
98
+
99
+ def not_empty?(val)
100
+ !!val == val || !val.to_s.strip.empty?
101
+ end
102
+
103
+ private
104
+
105
+ # Can be set to nil
106
+ def index_name=(val)
107
+ @index_name = val.nil? ? val : val.to_s
108
+ end
109
+
110
+ # Builds the exclusive_start_key if val is a Hash
111
+ def offset_key=(val)
112
+ @offset_key = val.stringify_keys if val.is_a?(Hash)
113
+ end
114
+
115
+ def build_query
116
+ query = {}
117
+ query.merge!({ table_name: source.table_name })
118
+ build_expressions
119
+ QUERY_METHODS.each do |meth|
120
+ val = self.send(meth)
121
+ query.merge!({ meth => val }) if not_empty?(val)
122
+ end
123
+ QUERY_INSTANCE_VARS.each do |var|
124
+ val = self.instance_variable_get("@_#{var.to_s}")
125
+ query.merge!({ var => val }) if not_empty?(val)
126
+ end
127
+ query
128
+ end
129
+
130
+ def add_attribute_name(name)
131
+ ni = @expression_attribute_names.size + 1
132
+ @expression_attribute_names.merge!({ "#n#{ni}" => name })
133
+ "#n#{ni}"
134
+ end
135
+
136
+ def add_attribute_value(values)
137
+ values = [values].flatten # Set to an array to handle BETWEEN operator
138
+ values.each_with_object([]) do |value, obj|
139
+ vi = @expression_attribute_values.size + 1
140
+ @expression_attribute_values.merge!({ ":v#{vi}" => value })
141
+ obj << ":v#{vi}"
142
+ end.join(" AND ")
143
+ end
144
+
145
+ def add_attribute_query(attr, val)
146
+ @attribute_expressors.merge!({ attr => val })
147
+ end
148
+
149
+ def build_expressions
150
+ reset_expressions
151
+
152
+ attribute_expressors.each do |k, v|
153
+ expression_type = _define_expression_type(k).to_sym
154
+ self.send(expression_type, k, v)
155
+ end
156
+ end
157
+
158
+ def reset_expressions
159
+ @expression_attribute_names = {}
160
+ @expression_attribute_values = {}
161
+ @key_condition_expression = []
162
+ @filter_expression = []
163
+ end
164
+
165
+ def _hash_expression=(k, v)
166
+ h_name = add_attribute_name(k.to_s)
167
+ h_value = add_attribute_value(v)
168
+ @key_condition_expression << "#{h_name} = #{h_value}"
169
+ end
170
+
171
+ def _range_expression=(k, v)
172
+ r_name = add_attribute_name(k.to_s)
173
+ r_op = OPERATOR_MAP[v.keys[0]]
174
+ r_value = add_attribute_value(v.values[0])
175
+ @key_condition_expression << "#{r_name} #{r_op} #{r_value}"
176
+ end
177
+
178
+ def _filter_expression=(k, v)
179
+ f_name = add_attribute_name(k.to_s)
180
+ f_op = OPERATOR_MAP[v.keys[0]]
181
+ f_value = add_attribute_value(v.values[0])
182
+ @filter_expression << "#{f_name} #{f_op} #{f_value}"
183
+ end
184
+
185
+ def _define_expression_type(key)
186
+ schema = _expression_schema.detect { |x| x[:attribute_name] == key.to_s }
187
+ schema ? "_#{schema[:key_type].downcase}_expression=" : "_filter_expression="
188
+ end
189
+
190
+ def _expression_schema
191
+ return source.key_schema if index_name.nil?
192
+
193
+ index = source.indexes.detect { |x| x[:index_name] == index_name }
194
+ index[:key_schema]
195
+ end
196
+ end
197
+ end
@@ -0,0 +1,79 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Dynamodb
4
+ module TableActions
5
+ def get_item(_table_name, _key, options = {})
6
+ _item = client.get_item(
7
+ {
8
+ table_name: _table_name,
9
+ key: _key
10
+ }.merge!(options)
11
+ )[:item]
12
+
13
+ _item ? item_to_object(_item) : nil
14
+ end
15
+
16
+ def put_item(_table_name, _item, options = {})
17
+ client.put_item(
18
+ {
19
+ table_name: _table_name,
20
+ item: _item
21
+ }.merge!(options)
22
+ )
23
+ end
24
+
25
+ def delete_item(_table_name, _key, options = {})
26
+ client.delete_item(
27
+ {
28
+ table_name: _table_name,
29
+ key: _key
30
+ }.merge!(options)
31
+ )
32
+ end
33
+
34
+ def _query(opts)
35
+ result = client.query(opts)
36
+ result.items = result.items.map { |x| item_to_object(x) }
37
+ result
38
+ end
39
+
40
+ def describe_table(_table_name)
41
+ client.describe_table(table_name: _table_name)
42
+ end
43
+
44
+ def list_tables
45
+ client.list_tables.table_names
46
+ end
47
+
48
+ def delete_table(_table_name)
49
+ # To prevent accidentally deleting tables in production
50
+ (raise "Can't delete tables in production") unless self.name == "Dynamodb" &&
51
+ self.config == { endpoint: "http://localhost:10070" }
52
+
53
+ client.delete_table(table_name: _table_name)
54
+ end
55
+
56
+ def create_table(_table_name, options)
57
+ # To prevent accidentally creating tables in production
58
+ (raise "Can't create tables in production") unless self.name == "Dynamodb" &&
59
+ self.config == { endpoint: "http://localhost:10070" }
60
+
61
+ resource.create_table(
62
+ {
63
+ table_name: _table_name,
64
+ provisioned_throughput: {
65
+ read_capacity_units: 5,
66
+ write_capacity_units: 5,
67
+ }
68
+ }.merge!(options)
69
+ )
70
+ end
71
+
72
+ private
73
+
74
+ # Converts a hash item result from dynamodb to object
75
+ def item_to_object(_item)
76
+ self.new(_item)
77
+ end
78
+ end
79
+ end
@@ -0,0 +1,3 @@
1
+ module Dynamodb
2
+ VERSION = "0.2.0"
3
+ end
metadata ADDED
@@ -0,0 +1,150 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: dynamodb-ruby
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.2.0
5
+ platform: ruby
6
+ authors:
7
+ - Steve Farrow
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2017-11-08 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: activesupport
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '5.0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '5.0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: aws-sdk-dynamodb
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '1'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '1'
41
+ - !ruby/object:Gem::Dependency
42
+ name: bundler
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '1.15'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '1.15'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rake
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '10.0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '10.0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: rspec
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '3.2'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '3.2'
83
+ - !ruby/object:Gem::Dependency
84
+ name: pry
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - ">="
88
+ - !ruby/object:Gem::Version
89
+ version: '0'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - ">="
95
+ - !ruby/object:Gem::Version
96
+ version: '0'
97
+ description: A small ORM wrapper to make working with AWS Dynamodb easier. Includes
98
+ Test helpers.
99
+ email:
100
+ - sfarrow@bandsintown.com
101
+ executables: []
102
+ extensions: []
103
+ extra_rdoc_files: []
104
+ files:
105
+ - ".gitignore"
106
+ - ".rspec"
107
+ - ".travis.yml"
108
+ - CODE_OF_CONDUCT.md
109
+ - Gemfile
110
+ - LICENSE.txt
111
+ - README.md
112
+ - Rakefile
113
+ - bin/console
114
+ - bin/setup
115
+ - dynamodb-ruby-0.1.0.gem
116
+ - dynamodb-ruby.gemspec
117
+ - lib/dynamodb.rb
118
+ - lib/dynamodb/attribute_assignment.rb
119
+ - lib/dynamodb/base.rb
120
+ - lib/dynamodb/connection.rb
121
+ - lib/dynamodb/local.rb
122
+ - lib/dynamodb/querying.rb
123
+ - lib/dynamodb/relation.rb
124
+ - lib/dynamodb/table_actions.rb
125
+ - lib/dynamodb/version.rb
126
+ homepage: https://www.bandsintown.com
127
+ licenses:
128
+ - MIT
129
+ metadata: {}
130
+ post_install_message:
131
+ rdoc_options: []
132
+ require_paths:
133
+ - lib
134
+ required_ruby_version: !ruby/object:Gem::Requirement
135
+ requirements:
136
+ - - ">="
137
+ - !ruby/object:Gem::Version
138
+ version: '0'
139
+ required_rubygems_version: !ruby/object:Gem::Requirement
140
+ requirements:
141
+ - - ">="
142
+ - !ruby/object:Gem::Version
143
+ version: '0'
144
+ requirements: []
145
+ rubyforge_project:
146
+ rubygems_version: 2.6.11
147
+ signing_key:
148
+ specification_version: 4
149
+ summary: A small ORM wrapper to make working with AWS Dynamodb easier.
150
+ test_files: []