dynamoid 3.14.0 → 3.15.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.
@@ -3,6 +3,30 @@
3
3
  module Dynamoid
4
4
  # This is the base module for all domain objects that need to be persisted to
5
5
  # the database as documents.
6
+ #
7
+ # == Single Table Inheritance (STI)
8
+ #
9
+ # Dynamoid supports Single Table Inheritance across class hierarchies stored
10
+ # in the same DynamoDB table. Subclasses share the base table, inherit fields,
11
+ # and automatically populate an STI type attribute when the +type+ field
12
+ # (or custom +inheritance_field+) is declared on the base class:
13
+ #
14
+ # class Animal
15
+ # include Dynamoid::Document
16
+ # field :name, :string
17
+ # field :type, :string
18
+ # end
19
+ #
20
+ # class Dog < Animal
21
+ # field :bark_volume, :integer
22
+ # end
23
+ #
24
+ # class Cat < Animal
25
+ # field :lives, :integer, default: 9
26
+ # end
27
+ #
28
+ # See {ClassMethods#inheritance_field}, {ClassMethods#sti_name}, {ClassMethods#sti_class_for}, and {ClassMethods#abstract_class}
29
+ # for customization hooks.
6
30
  module Document
7
31
  extend ActiveSupport::Concern
8
32
  include Dynamoid::Components
@@ -46,12 +70,15 @@ module Dynamoid
46
70
  options[:capacity_mode] || Dynamoid::Config.capacity_mode
47
71
  end
48
72
 
49
- # Returns the field name used to support STI for this table.
73
+ # Returns the field name used to store the Single Table Inheritance (STI)
74
+ # type attribute for this table.
50
75
  #
51
- # Default field name is +type+ but it can be overrided in the +table+
76
+ # Default field name is +type+ but it can be overridden in the +table+
52
77
  # method call.
53
78
  #
54
79
  # User.inheritance_field # => :type
80
+ #
81
+ # @return [Symbol] name of the inheritance field
55
82
  def inheritance_field
56
83
  options[:inheritance_field] || :type
57
84
  end
@@ -166,16 +193,53 @@ module Dynamoid
166
193
  end
167
194
  end
168
195
 
196
+ # Set whether this class is an abstract base class.
197
+ #
198
+ # Abstract classes do not store Single Table Inheritance (STI)
199
+ # type values or scope queries by type.
200
+ #
201
+ # class ApplicationModel
202
+ # include Dynamoid::Document
203
+ # self.abstract_class = true
204
+ # end
205
+ #
206
+ # @return [Boolean, nil]
207
+ #
169
208
  attr_accessor :abstract_class
170
209
 
210
+ # Returns true if the class is marked as an abstract class.
211
+ #
212
+ # @return [Boolean]
171
213
  def abstract_class?
172
214
  defined?(@abstract_class) && @abstract_class == true
173
215
  end
174
216
 
217
+ # Returns the string identifier stored in the Single Table Inheritance (STI)
218
+ # type attribute.
219
+ #
220
+ # Defaults to the class name. Override this method in subclasses to decouple
221
+ # the stored type value from the Ruby class name.
222
+ #
223
+ # class Car < Vehicle
224
+ # def self.sti_name
225
+ # 'sedan'
226
+ # end
227
+ # end
228
+ #
229
+ # @return [String]
175
230
  def sti_name
176
231
  name
177
232
  end
178
233
 
234
+ # Resolves a Single Table Inheritance (STI) type string into
235
+ # the corresponding model class.
236
+ #
237
+ # Override this method in the base class to provide custom class mapping
238
+ # or to resolve renamed or legacy type strings.
239
+ #
240
+ # @param type_name [String] type value stored in DynamoDB
241
+ # @return [Class] the resolved Dynamoid model class
242
+ # @raise [Dynamoid::Errors::SubclassNotFound] if the class constant cannot be resolved
179
243
  def sti_class_for(type_name)
180
244
  type_name.constantize
181
245
  rescue NameError
@@ -37,7 +37,7 @@ module Dynamoid
37
37
  when :raw then RawDumper
38
38
  when :boolean then BooleanDumper
39
39
  when :binary then BinaryDumper
40
- when Class then CustomTypeDumper
40
+ when Module then CustomTypeDumper
41
41
  end
42
42
 
43
43
  if dumper_class.present?
@@ -105,7 +105,7 @@ module Dynamoid
105
105
 
106
106
  # set -> set
107
107
  class SetDumper < Base
108
- ALLOWED_TYPES = %i[string integer number date datetime serialized].freeze
108
+ ALLOWED_TYPES = %i[string integer number date datetime serialized binary].freeze
109
109
 
110
110
  def process(set)
111
111
  return nil if set.is_a?(Set) && set.empty?
@@ -135,7 +135,7 @@ module Dynamoid
135
135
  end
136
136
 
137
137
  def allowed_type?
138
- ALLOWED_TYPES.include?(element_type) || element_type.is_a?(Class)
138
+ ALLOWED_TYPES.include?(element_type) || element_type.is_a?(Module)
139
139
  end
140
140
 
141
141
  def element_type
@@ -159,7 +159,7 @@ module Dynamoid
159
159
 
160
160
  # array -> array
161
161
  class ArrayDumper < Base
162
- ALLOWED_TYPES = %i[string integer number date datetime serialized].freeze
162
+ ALLOWED_TYPES = %i[string integer number date datetime serialized binary].freeze
163
163
 
164
164
  def process(array)
165
165
  if @options.key?(:of)
@@ -186,7 +186,7 @@ module Dynamoid
186
186
  end
187
187
 
188
188
  def allowed_type?
189
- ALLOWED_TYPES.include?(element_type) || element_type.is_a?(Class)
189
+ ALLOWED_TYPES.include?(element_type) || element_type.is_a?(Module)
190
190
  end
191
191
 
192
192
  def element_type
@@ -300,6 +300,8 @@ module Dynamoid
300
300
  # string -> StringIO
301
301
  class BinaryDumper < Base
302
302
  def process(value)
303
+ return nil if value.nil?
304
+
303
305
  store_as_binary = if @options[:store_as_native_binary].nil?
304
306
  Dynamoid.config.store_binary_as_native
305
307
  else
@@ -39,7 +39,7 @@ module Dynamoid
39
39
  warn_if_method_exists(@name)
40
40
  warn_if_method_exists("#{@name}=")
41
41
  warn_if_method_exists("#{@name}?")
42
- warn_if_method_exists("#{@name}_before_type_cast?")
42
+ warn_if_method_exists("#{@name}_before_type_cast")
43
43
  end
44
44
 
45
45
  def generate_instance_methods
@@ -54,7 +54,11 @@ module Dynamoid
54
54
  when true then true
55
55
  when false, nil then false
56
56
  else
57
- !value.nil?
57
+ if value.respond_to?(:zero?)
58
+ !value.zero?
59
+ else
60
+ !value.blank?
61
+ end
58
62
  end
59
63
  end
60
64
  define_method(:"#{name}=") { |value| write_attribute(name, value) }
@@ -39,7 +39,7 @@ module Dynamoid
39
39
  # Its type determines how it is coerced when read in and out of the
40
40
  # data store. You can specify +string+, +integer+, +number+, +set+, +array+,
41
41
  # +map+, +datetime+, +date+, +serialized+, +raw+, +boolean+ and +binary+
42
- # or specify a class that defines a serialization strategy.
42
+ # or specify a class or module that defines a serialization strategy.
43
43
  #
44
44
  # By default field type is +string+.
45
45
  #
@@ -78,8 +78,8 @@ module Dynamoid
78
78
  # string can be specified with +serializer+ option. Custom serializer
79
79
  # should have +dump+ and +load+ methods.
80
80
  #
81
- # If you specify a class for field type, Dynamoid will serialize using
82
- # +dynamoid_dump+ method and load using +dynamoid_load+ method.
81
+ # If you specify a class or module for a field type, Dynamoid will serialize
82
+ # using +dynamoid_dump+ and load using +dynamoid_load+.
83
83
  #
84
84
  # Default field type is +string+.
85
85
  #
@@ -138,7 +138,7 @@ module Dynamoid
138
138
  # ```
139
139
  #
140
140
  # @param name [Symbol] name of the field
141
- # @param type [Symbol] type of the field (optional)
141
+ # @param type [Symbol, Class, Module] type of the field (optional)
142
142
  # @param options [Hash] any additional options for the field type (optional)
143
143
  # @option options [Symbol] :of <description>
144
144
  # @option options [Symbol] :store_as_string <description>
@@ -176,67 +176,87 @@ module Dynamoid
176
176
  # range :date_of_birth, :date, store_as_string: true
177
177
  #
178
178
  # @param name [Symbol] a range key attribute name
179
- # @param type [Symbol] a range key type (optional)
179
+ # @param type [Symbol, Class, Module] a scalar range key type (+:string+, +:integer+,
180
+ # +:number+, +:date+, +:datetime+, +:binary+, +:serialized+, or a custom
181
+ # class or module implementing serialization; defaults to +:string+)
180
182
  # @param options [Hash] type options (optional)
181
183
  def range(name, type = :string, options = {})
182
184
  field(name, type, options)
183
185
  self.range_key = name
184
186
  end
185
187
 
186
- # Set table level properties.
188
+ # Set table-level properties, table name, and partition key configuration.
187
189
  #
188
- # There are some sensible defaults:
190
+ # Sensible defaults provided by Dynamoid:
189
191
  #
190
- # * table name is based on a model class e.g. +users+ for +User+ class
191
- # * hash key name - +id+ by default
192
- # * hash key type - +string+ by default
193
- # * generating timestamp fields +created_at+ and +updated_at+
194
- # * billing mode and read/write capacity units
192
+ # * Table name: inferred from model class name (e.g. +users+ for +User+ class)
193
+ # * Partition (hash) key name: +:id+
194
+ # * Partition key type: +:string+
195
+ # * Capacity mode: +:provisioned+ (or configured globally via +Dynamoid::Config.capacity_mode+)
196
+ # * Read/write capacity: +100+ / +20+ (or global config)
197
+ # * Timestamps: generates +created_at+ and +updated_at+ fields (+:datetime+)
195
198
  #
196
- # The +table+ method can be used to override the defaults:
199
+ # == Examples
197
200
  #
198
- # ```
199
- # class User
200
- # include Dynamoid::Document
201
+ # Basic table override:
201
202
  #
202
- # table name: :customers, key: :uuid
203
- # end
204
- # ```
203
+ # class Customer
204
+ # include Dynamoid::Document
205
205
  #
206
- # The hash key field is declared by default and a type is a string. If
207
- # another type is needed the field should be declared explicitly:
206
+ # table name: :clients, key: :client_id
207
+ # end
208
208
  #
209
- # ```
210
- # class User
211
- # include Dynamoid::Document
209
+ # Custom partition key with non-string type:
212
210
  #
213
- # field :id, :integer
214
- # end
215
- # ```
211
+ # class User
212
+ # include Dynamoid::Document
216
213
  #
217
- # To declare a new attribute with not-default type as a table hash key a
218
- # :key_type option can be used:
214
+ # table key: :user_id, key_type: :integer
215
+ # end
219
216
  #
220
- # ```
221
- # class User
222
- # include Dynamoid::Document
217
+ # Customizing the default +:id+ key type:
223
218
  #
224
- # table key: :user_id, key_type: :integer
225
- # end
226
- # ```
219
+ # class Product
220
+ # include Dynamoid::Document
221
+ #
222
+ # table key_type: :integer
223
+ # end
224
+ #
225
+ # On-demand billing and TTL:
226
+ #
227
+ # class Session
228
+ # include Dynamoid::Document
229
+ #
230
+ # table capacity_mode: :on_demand,
231
+ # expires: { field: :ttl, after: 86_400 }
232
+ #
233
+ # field :ttl, :integer
234
+ # end
235
+ #
236
+ # Using a table from another AWS account:
237
+ #
238
+ # class ExternalRecord
239
+ # include Dynamoid::Document
240
+ #
241
+ # table arn: 'arn:aws:dynamodb:us-east-1:123456789012:table/records'
242
+ # end
243
+ #
244
+ # @note Provisioning options (+read_capacity+, +write_capacity+, +capacity_mode+)
245
+ # and TTL (+expires+) only apply when Dynamoid creates a new DynamoDB table.
246
+ # Dynamoid does not alter existing tables in DynamoDB.
227
247
  #
228
248
  # @param options [Hash] options to override default table settings
229
- # @option options [Symbol] :name name of a table
230
- # @option options [Symbol] :arn table ARN; it allows referring tables in another AWS accounts; has higher priority than the +name+ option
231
- # @option options [Symbol] :key name of a hash key attribute
232
- # @option options [Symbol] :key_type type of a hash key attribute
233
- # @option options [Symbol] :inheritance_field name of an attribute used for STI
234
- # @option options [Array<Symbol>] :skip_generating_fields don't generate implicitly methods with given names, e.g. +:id+, +:created_at+, +:updated_at+
235
- # @option options [Symbol] :capacity_mode table billing mode - either +provisioned+ or +on_demand+
236
- # @option options [Integer] :write_capacity table write capacity units
237
- # @option options [Integer] :read_capacity table read capacity units
238
- # @option options [true|false] :timestamps whether generate +created_at+ and +updated_at+ fields or not
239
- # @option options [Hash] :expires set up a table TTL and should have following structure +{ field: <attriubute name>, after: <seconds> }+
249
+ # @option options [Symbol, String] :name name of a table
250
+ # @option options [String] :arn table ARN; allows referring to tables in another AWS account or region (takes precedence over +:name+)
251
+ # @option options [Symbol] :key name of the partition (hash) key attribute (defaults to +:id+)
252
+ # @option options [Symbol, Class, Module] :key_type scalar type of the partition key attribute (+:string+, +:integer+, +:number+, +:date+, +:datetime+, +:binary+, +:serialized+, or a custom class or module serialized as a string; defaults to +:string+)
253
+ # @option options [Symbol] :capacity_mode billing mode (+:provisioned+ or +:on_demand+)
254
+ # @option options [Integer] :read_capacity read capacity units for provisioned tables
255
+ # @option options [Integer] :write_capacity write capacity units for provisioned tables
256
+ # @option options [Boolean] :timestamps (true) whether to generate and maintain +created_at+ and +updated_at+ fields
257
+ # @option options [Hash] :expires configure DynamoDB TTL in format +{ field: <attribute_name>, after: <seconds> }+
258
+ # @option options [Symbol] :inheritance_field name of the discriminator attribute used for STI (defaults to +:type+)
259
+ # @option options [Array<Symbol>] :skip_generating_fields list of implicit fields to not generate (+:id+, +:created_at+, +:updated_at+)
240
260
  #
241
261
  # @since 0.4.0
242
262
  def table(options)
@@ -246,7 +266,7 @@ module Dynamoid
246
266
  timestamps_already_declared = Dynamoid::Config.timestamps
247
267
 
248
268
  # a default 'id' column is created when Dynamoid::Document is included
249
- unless attributes.key? hash_key
269
+ if !attributes.key?(hash_key) || (hash_key == :id && options[:key_type])
250
270
  remove_field :id
251
271
  id_already_declared = false
252
272
 
@@ -290,8 +310,7 @@ module Dynamoid
290
310
 
291
311
  # Remove a field declaration
292
312
  #
293
- # Removes a field from the list of fields and removes all te generated
294
- # for a field methods.
313
+ # Removes a field from the list of fields and removes all methods generated for that field.
295
314
  #
296
315
  # @param field [Symbol] a field name
297
316
  def remove_field(field)
@@ -338,6 +357,7 @@ module Dynamoid
338
357
  # @param name [Symbol] the name of the field
339
358
  # @param value [Object] the value to assign to that field
340
359
  # @return [Dynamoid::Document] self
360
+ # @raise [Dynamoid::Errors::UnknownAttribute] if the attribute is not declared on the model
341
361
  #
342
362
  # @since 0.2.0
343
363
  def write_attribute(name, value)
@@ -57,6 +57,50 @@ module Dynamoid
57
57
  end
58
58
  end
59
59
 
60
+ # Find objects by executing a PartiQL +SELECT+ statement.
61
+ #
62
+ # Executes the given PartiQL statement against DynamoDB and instantiates
63
+ # matching model instances, running +after_initialize+ and +after_find+
64
+ # callbacks.
65
+ #
66
+ # The table name in the statement must equal DynamoDB's table name (such
67
+ # as +User.table_name+). Bind parameter values are passed directly to
68
+ # DynamoDB without type casting or serialization (for example, +:datetime+
69
+ # and +:date+ values must be passed in their underlying storage format,
70
+ # such as numeric Unix epoch timestamps or ISO 8601 strings).
71
+ #
72
+ # Reads are eventually consistent by default. Pass +consistent_read: true+
73
+ # to perform a strongly consistent read.
74
+ #
75
+ # @param statement [String] PartiQL statement
76
+ # @param parameters [Array] a list of bind parameters (optional)
77
+ # @param options [Hash] (optional)
78
+ # @option options [true|false] :consistent_read perform a strongly consistent read
79
+ # @return [Array<Dynamoid::Document>] matching model instances
80
+ #
81
+ # @example Find all items
82
+ # User.find_by_partiql("SELECT * FROM #{User.table_name}")
83
+ #
84
+ # @example Find items with bind parameters
85
+ # User.find_by_partiql("SELECT * FROM #{User.table_name} WHERE name = ?", ['Alice'])
86
+ #
87
+ # @example Perform a strongly consistent read
88
+ # User.find_by_partiql("SELECT * FROM #{User.table_name} WHERE id = ?", ['101'], consistent_read: true)
89
+ def find_by_partiql(statement, parameters = [], options = {})
90
+ if parameters.is_a?(Hash) && options.empty?
91
+ options = parameters
92
+ parameters = []
93
+ end
94
+
95
+ items = Dynamoid.adapter.execute(statement, parameters, options.slice(:consistent_read))
96
+
97
+ items.map do |item|
98
+ model = from_database(item)
99
+ model.run_callbacks :find
100
+ model
101
+ end.to_a
102
+ end
103
+
60
104
  # Find several models at once.
61
105
  #
62
106
  # Returns objects found by the given array of ids, either hash keys, or
@@ -5,12 +5,13 @@ module Dynamoid
5
5
  extend ActiveSupport::Concern
6
6
 
7
7
  def self.clear
8
- Dynamoid.included_models.each { |m| m.identity_map.clear }
8
+ Thread.current[:dynamoid_identity_map]&.clear
9
9
  end
10
10
 
11
11
  module ClassMethods
12
12
  def identity_map
13
- @identity_map ||= {}
13
+ Thread.current[:dynamoid_identity_map] ||= {}
14
+ Thread.current[:dynamoid_identity_map][self] ||= {}
14
15
  end
15
16
 
16
17
  # @private
@@ -21,7 +21,7 @@ module Dynamoid
21
21
  end
22
22
 
23
23
  module ClassMethods
24
- # Defines a Global Secondary index on a table. Keys can be specified as
24
+ # Defines a Global Secondary Index (GSI) on a table. Keys can be specified as
25
25
  # hash-only, or hash & range.
26
26
  #
27
27
  # ```
@@ -45,27 +45,34 @@ module Dynamoid
45
45
  # write_capacity: 20
46
46
  # ```
47
47
  #
48
- # Global secondary index should be declared after fields for mentioned
49
- # hash key and optional range key are declared (with method +field+)
48
+ # Because +global_secondary_index+ resolves the table name and key field types
49
+ # immediately when called, it must be declared after +table+, +range+, and
50
+ # the referenced +field+ definitions.
50
51
  #
51
- # The only mandatory option is +hash_key+. Raises
52
- # +Dynamoid::Errors::InvalidIndex+ exception if passed incorrect
53
- # options.
52
+ # Referenced +:hash_key+ and +:range_key+ fields must use a scalar type supported
53
+ # by DynamoDB keys (+:string+, +:integer+, +:number+, +:date+, +:datetime+,
54
+ # +:binary+, +:serialized+, or a custom class or module implementing serialization).
54
55
  #
55
- # @param [Hash] options the options to pass for this table
56
- # @option options [Symbol] name the name for the index; this still gets
57
- # namespaced. If not specified, will use a default name.
58
- # @option options [Symbol] hash_key the index hash key column.
59
- # @option options [Symbol] range_key the index range key column (if
60
- # applicable).
61
- # @option options [Symbol, Array<Symbol>] projected_attributes table
62
- # attributes to project for this index. Can be +:keys_only+, +:all+
63
- # or an array of included fields. If not specified, defaults to
56
+ # @param [Hash] options the options to pass for this index
57
+ # @option options [Symbol] :hash_key the index partition (hash) key attribute (required).
58
+ # @option options [Symbol] :range_key the index sort (range) key attribute (optional).
59
+ # @option options [Symbol, String] :name explicit index name; used as-is without a table
60
+ # or namespace prefix. If omitted, a default name (+<table_name>_index_<keys>+)
61
+ # is generated.
62
+ # @option options [Symbol, Array<Symbol>] :projected_attributes table
63
+ # attributes to project into this index. Can be +:keys_only+, +:all+,
64
+ # or an array of attribute names (e.g. +[:title, :author]+). Defaults to
64
65
  # +:keys_only+.
65
- # @option options [Integer] read_capacity set the read capacity for the
66
- # index; does not work on existing indexes.
67
- # @option options [Integer] write_capacity set the write capacity for
68
- # the index; does not work on existing indexes.
66
+ # @option options [Integer] :read_capacity read capacity units for the index
67
+ # (defaults to +Dynamoid::Config.read_capacity+). Only applies when creating
68
+ # a provisioned table; ignored when the table uses +:on_demand+ capacity mode.
69
+ # @option options [Integer] :write_capacity write capacity units for the index
70
+ # (defaults to +Dynamoid::Config.write_capacity+). Only applies when creating
71
+ # a provisioned table; ignored when the table uses +:on_demand+ capacity mode.
72
+ # @raise [Dynamoid::Errors::InvalidIndex] if +options+ is empty, +:hash_key+ is missing,
73
+ # a referenced key field is not yet declared or is not a valid scalar key type,
74
+ # or +:projected_attributes+ is invalid.
75
+ # @return [Class] self
69
76
  def global_secondary_index(options = {})
70
77
  unless options.present?
71
78
  raise Dynamoid::Errors::InvalidIndex, 'empty index definition'
@@ -89,14 +96,14 @@ module Dynamoid
89
96
  self
90
97
  end
91
98
 
92
- # Defines a local secondary index on a table. Will use the same primary
93
- # hash key as the table.
99
+ # Defines a Local Secondary Index (LSI) on a table. Uses the same primary
100
+ # partition (hash) key as the table and requires an alternate +:range_key+.
94
101
  #
95
102
  # ```
96
103
  # class Comment
97
104
  # include Dynamoid::Document
98
105
  #
99
- # table hash_key: :post_id
106
+ # table key: :post_id
100
107
  # range :created_at, :datetime
101
108
  # field :author_id
102
109
  #
@@ -107,27 +114,33 @@ module Dynamoid
107
114
  # The full example with all the options being specified:
108
115
  #
109
116
  # ```
110
- # local_secondary_index range_key: :created_at,
111
- # name: 'posts_created_at_index',
117
+ # local_secondary_index range_key: :author_id,
118
+ # name: 'comments_author_id_index',
112
119
  # projected_attributes: :all
113
120
  # ```
114
121
  #
115
- # Local secondary index should be declared after fields for mentioned
116
- # hash key and optional range key are declared (with method +field+) as
117
- # well as after +table+ method call.
122
+ # Because +local_secondary_index+ resolves the table name, primary keys, and
123
+ # field types immediately when called, it must be declared after +table+,
124
+ # +range+, and the referenced +field+ definition.
118
125
  #
119
- # The only mandatory option is +range_key+. Raises
120
- # +Dynamoid::Errors::InvalidIndex+ exception if passed incorrect
121
- # options.
126
+ # The referenced +:range_key+ field must differ from the table's primary sort key
127
+ # and use a scalar type supported by DynamoDB keys (+:string+, +:integer+,
128
+ # +:number+, +:date+, +:datetime+, +:binary+, +:serialized+, or a custom class
129
+ # or module implementing serialization).
122
130
  #
123
- # @param [Hash] options options to pass for this index.
124
- # @option options [Symbol] name the name for the index; this still gets
125
- # namespaced. If not specified, a name is automatically generated.
126
- # @option options [Symbol] range_key the range key column for the index.
127
- # @option options [Symbol, Array<Symbol>] projected_attributes table
128
- # attributes to project for this index. Can be +:keys_only+, +:all+
129
- # or an array of included fields. If not specified, defaults to
131
+ # @param [Hash] options options to pass for this index
132
+ # @option options [Symbol] :range_key the index sort (range) key attribute (required).
133
+ # @option options [Symbol, String] :name explicit index name; used as-is without a table
134
+ # or namespace prefix. If omitted, a default name (+<table_name>_index_<keys>+)
135
+ # is generated.
136
+ # @option options [Symbol, Array<Symbol>] :projected_attributes table
137
+ # attributes to project into this index. Can be +:keys_only+, +:all+,
138
+ # or an array of attribute names (e.g. +[:title, :author]+). Defaults to
130
139
  # +:keys_only+.
140
+ # @raise [Dynamoid::Errors::InvalidIndex] if +options+ is empty, +:range_key+ is missing
141
+ # or matches the table's primary range key, a referenced key field is not yet
142
+ # declared or is not a valid scalar key type, or +:projected_attributes+ is invalid.
143
+ # @return [Class] self
131
144
  def local_secondary_index(options = {})
132
145
  unless options.present?
133
146
  raise Dynamoid::Errors::InvalidIndex, 'empty index definition'
@@ -17,6 +17,9 @@ module Dynamoid
17
17
 
18
18
  def call
19
19
  models = @array_of_attributes.map(&method(:build_model))
20
+ models.each do |model|
21
+ validate_primary_key!(model)
22
+ end
20
23
 
21
24
  unless Dynamoid.config.backoff
22
25
  import(models)
@@ -43,10 +46,21 @@ module Dynamoid
43
46
  end
44
47
 
45
48
  @model_class.build(attrs).tap do |model|
46
- model.hash_key = SecureRandom.uuid if model.hash_key.blank?
49
+ if model.hash_key.nil? && hash_key_string?
50
+ model.hash_key = SecureRandom.uuid
51
+ end
47
52
  end
48
53
  end
49
54
 
55
+ def validate_primary_key!(model)
56
+ raise Dynamoid::Errors::MissingHashKey if model.hash_key.nil?
57
+ raise Dynamoid::Errors::MissingRangeKey if @model_class.range_key? && model.range_value.nil?
58
+ end
59
+
60
+ def hash_key_string?
61
+ @model_class.attributes[@model_class.hash_key][:type] == :string
62
+ end
63
+
50
64
  def import_with_backoff(models)
51
65
  backoff = nil
52
66
  table_name = @model_class.table_name
@@ -6,19 +6,17 @@ module Dynamoid
6
6
  module Persistence
7
7
  # @private
8
8
  class Inc
9
- def self.call(model_class, partition_key, sort_key = nil, counters) # rubocop:disable Style/OptionalArguments
10
- new(model_class, partition_key, sort_key, counters).call
9
+ def self.call(model_class, partition_key, sort_key, **counters)
10
+ new(model_class, partition_key, sort_key, **counters).call
11
11
  end
12
12
 
13
- # rubocop:disable Style/OptionalArguments
14
- def initialize(model_class, partition_key, sort_key = nil, counters)
13
+ def initialize(model_class, partition_key, sort_key, **counters)
15
14
  @model_class = model_class
16
15
  @partition_key = partition_key
17
16
  @sort_key = sort_key
18
17
  @counters = counters
19
18
  @touch = @counters.delete(:touch)
20
19
  end
21
- # rubocop:enable Style/OptionalArguments
22
20
 
23
21
  def call
24
22
  validate_primary_key!
@@ -16,9 +16,11 @@ module Dynamoid
16
16
  end
17
17
 
18
18
  def call
19
- validate_primary_key!
19
+ if @model.new_record? && @model.hash_key.nil? && hash_key_string?
20
+ @model.hash_key = SecureRandom.uuid
21
+ end
20
22
 
21
- @model.hash_key = SecureRandom.uuid if @model.hash_key.blank?
23
+ validate_primary_key!
22
24
 
23
25
  return true unless @model.changed?
24
26
 
@@ -69,10 +71,14 @@ module Dynamoid
69
71
  private
70
72
 
71
73
  def validate_primary_key!
72
- raise Dynamoid::Errors::MissingHashKey if !@model.new_record? && @model.hash_key.nil?
74
+ raise Dynamoid::Errors::MissingHashKey if @model.hash_key.nil?
73
75
  raise Dynamoid::Errors::MissingRangeKey if @model.class.range_key? && @model.range_value.nil?
74
76
  end
75
77
 
78
+ def hash_key_string?
79
+ @model.class.attributes[@model.class.hash_key][:type] == :string
80
+ end
81
+
76
82
  # Should be called after incrementing `lock_version` attribute
77
83
  def conditions_to_create_item
78
84
  conditions = {}