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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: da9e734377895a7f4bdf90218757bf03f6d7ffeb18661a858dcfab5977065d0c
4
- data.tar.gz: e7276b6f31cd7a7999c679cf1d5b96b4c25278949bebd09dcd88e4dd64e38c3d
3
+ metadata.gz: 2e0995a9add15f716d77ec11cbad76e4f17eeaeeaec40fe4b0728a6716ce37df
4
+ data.tar.gz: 2eef23fc80570d3860791efd6517362de7c09346b0bc1b30a64cff4a5fd6c4ed
5
5
  SHA512:
6
- metadata.gz: d4b5fa9bd1573d3443397661ab7b6bff21d1f50fa7b665ca19022d928e270652539558af53f4fcd56dc53db8181e2a59439a05981726cbaf4bf5d05f4bf440ef
7
- data.tar.gz: b609e4cdf51b3057d022159e0d080a456df2dc40806cfbf22ec35fadb56f7547b9eada4c5cbfb339fcd4d2a2555019379811ec55b521fc922c576fb79a2a0137
6
+ metadata.gz: 00c2f28a0ff8a3f56e08546bddb7a0d6942e6d1c51a9feecca92a7a8db9548961a38132ada38d15b59c8469e1706e2e847cd9e17dbc64ca46ae6a8a95b2b9f4c
7
+ data.tar.gz: f78c29fdd5beb21dd894ca754c968e601f895f74b4f4393affeaa4802bdfe14106dcdd2b7edc08d33c11bfaa824df178103d18415bb5365b3c8669284fae64c2
data/CHANGELOG.md CHANGED
@@ -11,6 +11,40 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
11
11
  ### Changed
12
12
  ### Removed
13
13
 
14
+ ## 3.15.0 / 2026-11-30
15
+
16
+ ### Fixed
17
+ * [#1084](https://github.com/Dynamoid/dynamoid/pull/1084) Fix emitting a warning when a generated `<name>_before_type_cast` method is overridden
18
+ * [#1085](https://github.com/Dynamoid/dynamoid/pull/1085) Fix `Dynamoid::IdentityMap` to be thread-scoped
19
+ * [#1086](https://github.com/Dynamoid/dynamoid/pull/1086) Fix `#delete_all` to return the count of deleted items
20
+ * [#1087](https://github.com/Dynamoid/dynamoid/pull/1087) Fix `#destroy_all` to run `destroy` callbacks and return destroyed models
21
+ * [#1090](https://github.com/Dynamoid/dynamoid/pull/1090) Fix `#find_by_pages` to pass `models` and `options` as separate block arguments instead of a 2-element array
22
+ * [#1091](https://github.com/Dynamoid/dynamoid/pull/1091) Fix `#save` and `#import` (both transactional and non-transactional) to:
23
+ * auto-generate a UUID partition key only when its type is `:string`
24
+ * raise `MissingHashKey` or `MissingRangeKey` when the partition or sort key is `nil`
25
+ * [#1094](https://github.com/Dynamoid/dynamoid/pull/1094) Fix `#increment!` and `#decrement!` (both transactional and non-transactional) to run `touch` callbacks only when the `:touch` option is truthy
26
+ * [#1096](https://github.com/Dynamoid/dynamoid/pull/1096) Fix transactional `#import` to check primary key uniqueness and prevent overwriting existing items
27
+ * [#1097](https://github.com/Dynamoid/dynamoid/pull/1097) Fix `#update!` to raise `RecordNotSaved` (and `#update` to return `false` without clearing dirty changes) when an `update` callback throws `:abort`
28
+ ### Added
29
+ * [#1049](https://github.com/Dynamoid/dynamoid/pull/1049) Add `http_proxy` config option
30
+ * [#1051](https://github.com/Dynamoid/dynamoid/pull/1051) Add `use_yaml_unsafe_load` and `yaml_permitted_classes` config options for `:serialized` fields
31
+ * [#1081](https://github.com/Dynamoid/dynamoid/pull/1081) Add `Dynamoid::TestHelper` module to simplify table management in application tests:
32
+ * `Dynamoid::TestHelper.create_tables`
33
+ * `Dynamoid::TestHelper.truncate_tables`
34
+ * `Dynamoid::TestHelper.drop_tables`
35
+ * [#1093](https://github.com/Dynamoid/dynamoid/pull/1093) Add high-level methods for PartiQL operations:
36
+ * `.find_by_partiql`
37
+ * `.execute_partiql`
38
+ ### Changed
39
+ * [#1082](https://github.com/Dynamoid/dynamoid/pull/1082) Allow `:binary` partition and sort keys at table creation
40
+ * [#1083](https://github.com/Dynamoid/dynamoid/pull/1083) Allow calling `.with_index` directly on a model class
41
+ * [#1088](https://github.com/Dynamoid/dynamoid/pull/1088) Support `Module` as a field custom type
42
+ * [#1089](https://github.com/Dynamoid/dynamoid/pull/1089) Align generated `<name>?` predicate methods with ActiveRecord:
43
+ * return `false` for `0` and `0.0`
44
+ * return `false` for blank values (empty or whitespace-only strings, empty arrays, sets, and maps)
45
+ * [#1092](https://github.com/Dynamoid/dynamoid/pull/1092) Allow `:binary` elements in typed `set` and `array` fields
46
+ * [#1095](https://github.com/Dynamoid/dynamoid/pull/1095) Support `:key_type` option without `:key` in `.table`
47
+
14
48
  ## 3.14.0 / 2026-07-26
15
49
 
16
50
  ### Fixed
data/README.md CHANGED
@@ -14,21 +14,20 @@
14
14
  [![Keep-A-Changelog 1.0.0][📗keep-changelog-img]][📗keep-changelog]
15
15
  [![Sponsor Project][🖇sponsor-img]][🖇sponsor]
16
16
 
17
-
18
- A feature-rich and powerful Ruby ORM for Amazon DynamoDB, designed to provide a familiar ActiveRecord-like experience for Ruby applications.
19
-
17
+ Dynamoid is an Object-Document Mapper (ODM) for Amazon DynamoDB written in Ruby. It provides a familiar Active Record interface for Rails and standalone applications, letting you model, validate, and query DynamoDB items as expressive Ruby objects instead of raw AWS SDK parameter hashes.
20
18
 
21
19
  ## Key Features
22
20
 
23
- * ActiveRecord-style DSL: Implements an interface and configuration similar to Rails' ActiveRecord.
24
- * Querying & Persistence: Provides methods for finding, querying, and updating models.
25
- * Advanced ORM Features: Supports associations, callbacks, validations, Dirty API, optimistic locking, and type casting.
26
- * Additional Attribute Types: Supports types not natively provided by Amazon DynamoDB, such as `DateTime`, `Time`, and more.
27
- * Transactions: Supports Amazon DynamoDB transactional operations.
28
-
21
+ Dynamoid combines the familiar ergonomics of Rails' Active Record with the unique power of Amazon DynamoDB:
29
22
 
30
- ## Quick start
23
+ * *Active Record fidelity* — declare models, associations, validations, callbacks, dirty tracking, optimistic locking, and STI following standard Rails conventions.
24
+ * *Convention over configuration* — automatic table naming, UUID partition keys, and automatic timestamps so models work out of the box with minimal setup.
25
+ * *Query interface* — chain queries using ActiveRecord syntax while Dynamoid automatically routes to fast Query operations and selects secondary indexes over full-table Scans.
26
+ * *Native DynamoDB mutations* — perform atomic in-place updates on numbers and collections, conditional writes, and high-throughput bulk imports.
27
+ * *ACID transactions* — coordinate all-or-nothing reads and writes across multiple items and tables with full transactional guarantees.
28
+ * *Transparent attribute serialization* — persist types not native to DynamoDB (`Date`, `DateTime`), serialize objects into strings (YAML by default), and support custom classes implementing dump and load methods.
31
29
 
30
+ ## Quick Start
32
31
 
33
32
  ### Installation
34
33
 
@@ -38,101 +37,131 @@ Add Dynamoid to your `Gemfile`:
38
37
  gem 'dynamoid'
39
38
  ```
40
39
 
41
- Or install it using `bundle`:
40
+ Or install it with Bundler:
42
41
 
43
42
  ```shell
44
43
  bundle add dynamoid
45
44
  ```
46
45
 
47
- Alternatively, you can install the gem manually:
46
+ ### Configuration
48
47
 
49
- ```shell
50
- gem install dynamoid
48
+ Configure Dynamoid in `config/initializers/dynamoid.rb` (for Rails) or during application setup.
49
+
50
+ For local development and testing without an AWS account, point Dynamoid to [DynamoDB Local](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBLocal.html):
51
+
52
+ ```ruby
53
+ require 'dynamoid'
54
+
55
+ Dynamoid.configure do |config|
56
+ config.namespace = "my_app_#{defined?(Rails) ? Rails.env : 'development'}"
57
+ config.endpoint = 'http://localhost:8000'
58
+ config.region = 'us-east-1'
59
+ config.access_key = 'fake'
60
+ config.secret_key = 'fake'
61
+ end
51
62
  ```
52
63
 
64
+ When connecting to Amazon DynamoDB, credentials and region are discovered automatically from environment variables, AWS profiles, or IAM roles:
53
65
 
54
- ### Usage
66
+ ```ruby
67
+ Dynamoid.configure do |config|
68
+ config.namespace = "my_app_#{Rails.env}"
69
+ end
70
+ ```
71
+
72
+ ### Defining a Model
55
73
 
56
- To define a model, include `Dynamoid::Document` and declare your fields. Dynamoid supports ActiveModel validations and automatic timestamps:
74
+ Include `Dynamoid::Document` in your model class and declare attributes with `field`:
57
75
 
58
76
  ```ruby
59
- class User
77
+ class Order
60
78
  include Dynamoid::Document
61
79
 
62
- field :name # Type defaults to :string
63
- field :email
64
- field :age, :integer
65
- field :active, :boolean, default: true
80
+ field :customer_id
81
+ field :status, :string, default: 'pending'
82
+ field :amount, :number, default: 0
66
83
 
67
- validates :name, presence: true
68
- validates :email, format: { with: /@/ }
84
+ validates :customer_id, presence: true
85
+
86
+ before_save { self.status = status.downcase }
69
87
  end
70
88
  ```
71
89
 
72
- Once defined, you can interact with your models using a familiar API:
90
+ By default, the table name is derived from the pluralized class name (`orders`), the primary key is an auto-generated string UUID named `id`, and timestamps (`created_at`, `updated_at`) are maintained automatically.
91
+
92
+ ### Usage
93
+
94
+ #### Active Record CRUD
73
95
 
74
96
  ```ruby
75
- # Create and Save
76
- user = User.create(name: 'Josh', email: 'josh@example.com')
97
+ order = Order.create(customer_id: 'cust_101', amount: 95)
98
+ order = Order.find(order.id)
99
+ order.status = 'processing'
100
+ order.save
101
+ order.update_attributes(status: 'completed')
102
+ order.destroy
103
+ ```
77
104
 
78
- # Find and Update
79
- user = User.where(email: 'josh@example.com').first
80
- user.update_attributes(age: 30)
105
+ #### Querying
81
106
 
82
- # Querying
83
- users = User.where(active: true).all.to_a
107
+ ```ruby
108
+ pending = Order.where(status: 'pending').all
109
+ recent = Order.where(customer_id: 'cust_101', 'created_at.gte': 1.day.ago).all
84
110
  ```
85
111
 
112
+ #### Atomic In-Place Updates
86
113
 
87
- ### Essential Configuration
114
+ ```ruby
115
+ order = Order.find(order_id)
116
+ order.update(if: { status: 'processing' }) do |updater|
117
+ updater.set status: 'completed'
118
+ updater.add amount: 10
119
+ end
120
+ ```
88
121
 
89
- Minimal connection settings are required. You can configure Dynamoid in several ways, such as in `config/initializers/dynamoid.rb` (for Rails) or directly in your setup:
122
+ #### ACID Transactions
90
123
 
91
124
  ```ruby
92
- require 'dynamoid'
125
+ order = Order.find(order_id)
93
126
 
94
- Dynamoid.configure do |config|
95
- config.access_key = 'REPLACE_WITH_ACCESS_KEY_ID'
96
- config.secret_key = 'REPLACE_WITH_SECRET_ACCESS_KEY'
97
- config.region = 'REPLACE_WITH_REGION' # e.g. 'us-west-2'
127
+ Order.transaction do |t|
128
+ t.update_attributes(order, status: 'archived')
129
+ t.create(Order, customer_id: 'cust_102', amount: 50)
98
130
  end
99
131
  ```
100
132
 
101
-
102
133
  ## Documentation
103
134
 
104
- * **API Reference:** Comprehensive documentation for all classes and methods is available on [API Reference](https://dynamoid.github.io/dynamoid/reference/).
105
- * **User Guides:** For detailed overviews and usage examples of specific features, see the online [User Guides](https://dynamoid.github.io/dynamoid/guides/).
135
+ Comprehensive documentation is available on the project documentation site:
106
136
 
137
+ * [User Guides](https://dynamoid.github.io/dynamoid/guides/) — In-depth guides covering schema modeling, querying, persistence, transactions, and operational configuration.
138
+ * [API Reference](https://dynamoid.github.io/dynamoid/reference/) — Complete class and method reference generated from source code documentation.
107
139
 
108
140
  ## Compatibility
109
141
 
110
- Dynamoid relies on `aws-sdk-dynamodb` (AWS SDK v3) and `activemodel` (>= 4.2). It officially supports Ruby >= 2.3 and Rails >= 4.2.
111
-
112
- Compatibility is tested against the following versions:
113
- * Ruby: 2.3 - 4.0 (including JRuby 10.x)
114
- * Rails: 4.2 - 8.1
142
+ Dynamoid requires `aws-sdk-dynamodb` (AWS SDK v3) and `activemodel` (>= 4.2).
115
143
 
144
+ Continuous integration tests actively verify correctness against:
145
+ * Ruby: 2.3 – 4.0 (including JRuby 10.x)
146
+ * Rails / ActiveModel: 4.2 – 8.1
116
147
 
117
148
  ## Contributing
118
149
 
119
- We welcome contributions to Dynamoid! Please see our [CONTRIBUTING.md][contributing] guide for details on how to get started. Join us!
120
-
150
+ Please see [CONTRIBUTING.md][contributing] for details on how to get started.
121
151
 
122
152
  ## Security
123
153
 
124
- See [SECURITY.md][security].
125
-
154
+ Please see [SECURITY.md][security] for vulnerability reporting guidelines.
126
155
 
127
156
  ## License
128
157
 
129
- The gem is available as open source under the terms of
130
- the [MIT License][license] [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)][license-ref].
158
+ The gem is available as open source under the terms of the [MIT License][license] [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)][license-ref].
131
159
  See [LICENSE][license] for the official [Copyright Notice][copyright-notice-explainer].
132
160
 
133
-
134
161
  ## Credits
135
162
 
163
+ Dynamoid was originally created in 2012 by [Josh Symonds](https://github.com/joshsymonds) ([original repository](https://github.com/joshsymonds/Dynamoid)). Historical issues and discussions prior to the project's migration in 2015 can still be found in the [legacy issue tracker](https://github.com/joshsymonds/Dynamoid/issues).
164
+
136
165
  Dynamoid borrows code, structure, and even its name very liberally from
137
166
  the truly amazing [Mongoid](https://github.com/mongoid/mongoid). Without
138
167
  Mongoid to crib from none of this would have been possible, and I hope
@@ -103,7 +103,7 @@ module Dynamoid
103
103
  #
104
104
  # Keep in sync with AwsSdkV3.sanitize_item.
105
105
  def sanitize_attributes(attributes)
106
- # rubocop:disable Lint/DuplicateBranch
106
+ # rubocop:disable-next Lint/DuplicateBranch
107
107
  attributes.transform_values do |v|
108
108
  if v.is_a?(Hash)
109
109
  v.stringify_keys
@@ -115,7 +115,6 @@ module Dynamoid
115
115
  v
116
116
  end
117
117
  end
118
- # rubocop:enable Lint/DuplicateBranch
119
118
  end
120
119
  end
121
120
  end
@@ -44,72 +44,7 @@ module Dynamoid
44
44
  }
45
45
  BATCH_WRITE_ITEM_REQUESTS_LIMIT = 25
46
46
 
47
- CONNECTION_CONFIG_OPTIONS = %i[endpoint region http_continue_timeout http_idle_timeout http_open_timeout http_read_timeout].freeze
48
-
49
- # See https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ReservedWords.html
50
- # rubocop:disable Metrics/CollectionLiteralLength
51
- RESERVED_WORDS = Set.new(
52
- %i[
53
- ABORT ABSOLUTE ACTION ADD AFTER AGENT AGGREGATE ALL ALLOCATE ALTER ANALYZE
54
- AND ANY ARCHIVE ARE ARRAY AS ASC ASCII ASENSITIVE ASSERTION ASYMMETRIC AT
55
- ATOMIC ATTACH ATTRIBUTE AUTH AUTHORIZATION AUTHORIZE AUTO AVG BACK BACKUP
56
- BASE BATCH BEFORE BEGIN BETWEEN BIGINT BINARY BIT BLOB BLOCK BOOLEAN BOTH
57
- BREADTH BUCKET BULK BY BYTE CALL CALLED CALLING CAPACITY CASCADE CASCADED
58
- CASE CAST CATALOG CHAR CHARACTER CHECK CLASS CLOB CLOSE CLUSTER CLUSTERED
59
- CLUSTERING CLUSTERS COALESCE COLLATE COLLATION COLLECTION COLUMN COLUMNS
60
- COMBINE COMMENT COMMIT COMPACT COMPILE COMPRESS CONDITION CONFLICT CONNECT
61
- CONNECTION CONSISTENCY CONSISTENT CONSTRAINT CONSTRAINTS CONSTRUCTOR
62
- CONSUMED CONTINUE CONVERT COPY CORRESPONDING COUNT COUNTER CREATE CROSS
63
- CUBE CURRENT CURSOR CYCLE DATA DATABASE DATE DATETIME DAY DEALLOCATE DEC
64
- DECIMAL DECLARE DEFAULT DEFERRABLE DEFERRED DEFINE DEFINED DEFINITION
65
- DELETE DELIMITED DEPTH DEREF DESC DESCRIBE DESCRIPTOR DETACH DETERMINISTIC
66
- DIAGNOSTICS DIRECTORIES DISABLE DISCONNECT DISTINCT DISTRIBUTE DO DOMAIN
67
- DOUBLE DROP DUMP DURATION DYNAMIC EACH ELEMENT ELSE ELSEIF EMPTY ENABLE
68
- END EQUAL EQUALS ERROR ESCAPE ESCAPED EVAL EVALUATE EXCEEDED EXCEPT
69
- EXCEPTION EXCEPTIONS EXCLUSIVE EXEC EXECUTE EXISTS EXIT EXPLAIN EXPLODE
70
- EXPORT EXPRESSION EXTENDED EXTERNAL EXTRACT FAIL FALSE FAMILY FETCH FIELDS
71
- FILE FILTER FILTERING FINAL FINISH FIRST FIXED FLATTERN FLOAT FOR FORCE
72
- FOREIGN FORMAT FORWARD FOUND FREE FROM FULL FUNCTION FUNCTIONS GENERAL
73
- GENERATE GET GLOB GLOBAL GO GOTO GRANT GREATER GROUP GROUPING HANDLER HASH
74
- HAVE HAVING HEAP HIDDEN HOLD HOUR IDENTIFIED IDENTITY IF IGNORE IMMEDIATE
75
- IMPORT IN INCLUDING INCLUSIVE INCREMENT INCREMENTAL INDEX INDEXED INDEXES
76
- INDICATOR INFINITE INITIALLY INLINE INNER INNTER INOUT INPUT INSENSITIVE
77
- INSERT INSTEAD INT INTEGER INTERSECT INTERVAL INTO INVALIDATE IS ISOLATION
78
- ITEM ITEMS ITERATE JOIN KEY KEYS LAG LANGUAGE LARGE LAST LATERAL LEAD
79
- LEADING LEAVE LEFT LENGTH LESS LEVEL LIKE LIMIT LIMITED LINES LIST LOAD
80
- LOCAL LOCALTIME LOCALTIMESTAMP LOCATION LOCATOR LOCK LOCKS LOG LOGED LONG
81
- LOOP LOWER MAP MATCH MATERIALIZED MAX MAXLEN MEMBER MERGE METHOD METRICS
82
- MIN MINUS MINUTE MISSING MOD MODE MODIFIES MODIFY MODULE MONTH MULTI
83
- MULTISET NAME NAMES NATIONAL NATURAL NCHAR NCLOB NEW NEXT NO NONE NOT NULL
84
- NULLIF NUMBER NUMERIC OBJECT OF OFFLINE OFFSET OLD ON ONLINE ONLY OPAQUE
85
- OPEN OPERATOR OPTION OR ORDER ORDINALITY OTHER OTHERS OUT OUTER OUTPUT
86
- OVER OVERLAPS OVERRIDE OWNER PAD PARALLEL PARAMETER PARAMETERS PARTIAL
87
- PARTITION PARTITIONED PARTITIONS PATH PERCENT PERCENTILE PERMISSION
88
- PERMISSIONS PIPE PIPELINED PLAN POOL POSITION PRECISION PREPARE PRESERVE
89
- PRIMARY PRIOR PRIVATE PRIVILEGES PROCEDURE PROCESSED PROJECT PROJECTION
90
- PROPERTY PROVISIONING PUBLIC PUT QUERY QUIT QUORUM RAISE RANDOM RANGE RANK
91
- RAW READ READS REAL REBUILD RECORD RECURSIVE REDUCE REF REFERENCE
92
- REFERENCES REFERENCING REGEXP REGION REINDEX RELATIVE RELEASE REMAINDER
93
- RENAME REPEAT REPLACE REQUEST RESET RESIGNAL RESOURCE RESPONSE RESTORE
94
- RESTRICT RESULT RETURN RETURNING RETURNS REVERSE REVOKE RIGHT ROLE ROLES
95
- ROLLBACK ROLLUP ROUTINE ROW ROWS RULE RULES SAMPLE SATISFIES SAVE SAVEPOINT
96
- SCAN SCHEMA SCOPE SCROLL SEARCH SECOND SECTION SEGMENT SEGMENTS SELECT SELF
97
- SEMI SENSITIVE SEPARATE SEQUENCE SERIALIZABLE SESSION SET SETS SHARD SHARE
98
- SHARED SHORT SHOW SIGNAL SIMILAR SIZE SKEWED SMALLINT SNAPSHOT SOME SOURCE
99
- SPACE SPACES SPARSE SPECIFIC SPECIFICTYPE SPLIT SQL SQLCODE SQLERROR
100
- SQLEXCEPTION SQLSTATE SQLWARNING START STATE STATIC STATUS STORAGE STORE
101
- STORED STREAM STRING STRUCT STYLE SUB SUBMULTISET SUBPARTITION SUBSTRING
102
- SUBTYPE SUM SUPER SYMMETRIC SYNONYM SYSTEM TABLE TABLESAMPLE TEMP TEMPORARY
103
- TERMINATED TEXT THAN THEN THROUGHPUT TIME TIMESTAMP TIMEZONE TINYINT TO
104
- TOKEN TOTAL TOUCH TRAILING TRANSACTION TRANSFORM TRANSLATE TRANSLATION
105
- TREAT TRIGGER TRIM TRUE TRUNCATE TTL TUPLE TYPE UNDER UNDO UNION UNIQUE UNIT
106
- UNKNOWN UNLOGGED UNNEST UNPROCESSED UNSIGNED UNTIL UPDATE UPPER URL USAGE
107
- USE USER USERS USING UUID VACUUM VALUE VALUED VALUES VARCHAR VARIABLE
108
- VARIANCE VARINT VARYING VIEW VIEWS VIRTUAL VOID WAIT WHEN WHENEVER WHERE
109
- WHILE WINDOW WITH WITHIN WITHOUT WORK WRAPPED WRITE YEAR ZONE
110
- ]
111
- ).freeze
112
- # rubocop:enable Metrics/CollectionLiteralLength
47
+ CONNECTION_CONFIG_OPTIONS = %i[endpoint region http_continue_timeout http_idle_timeout http_open_timeout http_read_timeout http_proxy].freeze
113
48
 
114
49
  attr_reader :table_cache
115
50
 
@@ -156,9 +91,7 @@ module Dynamoid
156
91
  # Return the client object.
157
92
  #
158
93
  # @since 1.0.0
159
- def client
160
- @client
161
- end
94
+ attr_reader :client
162
95
 
163
96
  # Puts multiple items in one table
164
97
  #
@@ -2,6 +2,8 @@
2
2
 
3
3
  require 'uri'
4
4
  require 'logger'
5
+ require 'date'
6
+ require 'set'
5
7
  require 'dynamoid/config/options'
6
8
  require 'dynamoid/config/backoff_strategies/constant_backoff'
7
9
  require 'dynamoid/config/backoff_strategies/exponential_backoff'
@@ -19,7 +21,7 @@ module Dynamoid
19
21
  'dynamoid'
20
22
  end
21
23
 
22
- extend self
24
+ extend self # rubocop:disable Style/ModuleFunction
23
25
 
24
26
  extend Options
25
27
  include ActiveModel::Observing if defined?(ActiveModel::Observing)
@@ -62,7 +64,14 @@ module Dynamoid
62
64
  option :http_idle_timeout, default: nil # - default: 5
63
65
  option :http_open_timeout, default: nil # - default: 15
64
66
  option :http_read_timeout, default: nil # - default: 60
67
+ option :http_proxy, default: nil
65
68
  option :create_table_on_save, default: true
69
+ # Maintain backward compatibility: safe loading was unconditionally
70
+ # introduced in Dynamoid 3.8.0 for Ruby >= 3.1.
71
+ option :use_yaml_unsafe_load, default: Gem::Version.new(RUBY_VERSION) < Gem::Version.new('3.1.0')
72
+ # Default list introduced in Dynamoid 3.8.0; kept for backward
73
+ # compatibility until the next major version.
74
+ option :yaml_permitted_classes, default: [Symbol, Set, Date, Time, DateTime]
66
75
 
67
76
  # The default logger for Dynamoid: either the Rails logger or just stdout.
68
77
  #
@@ -96,6 +96,10 @@ module Dynamoid
96
96
  # Post.where('size.gt' => 100).where('size.lt' => 200)
97
97
  #
98
98
  # Internally +where+ performs either +Scan+ or +Query+ operation.
99
+ # When conditions do not include an equality condition on a partition key,
100
+ # it falls back to a +Scan+. If +Dynamoid::Config.error_on_scan+ is enabled
101
+ # and conditions are non-empty, executing the query raises
102
+ # +Dynamoid::Errors::ScanProhibited+ (unconditional scans such as +Model.all+ are allowed).
99
103
  #
100
104
  # Conditions can be specified as an expression as well:
101
105
  #
@@ -110,6 +114,8 @@ module Dynamoid
110
114
  # - https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.OperatorsAndFunctions.html
111
115
  # - https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.FilterExpression.html
112
116
  #
117
+ # @raise [Dynamoid::Errors::ScanProhibited] if +Dynamoid::Config.error_on_scan+ is enabled
118
+ # and non-empty conditions fall back to a +Scan+ operation upon execution.
113
119
  # @return [Dynamoid::Criteria::Chain]
114
120
  # @since 0.2.0
115
121
  def where(conditions, placeholders = nil)
@@ -230,6 +236,8 @@ module Dynamoid
230
236
  # deletes them in batch with +BatchWriteItem+ operation. +BatchWriteItem+
231
237
  # is limited by request size and items count so it's quite possible the
232
238
  # deletion will require several +BatchWriteItem+ calls.
239
+ #
240
+ # @return [Integer] the number of deleted items
233
241
  def delete_all
234
242
  ids = []
235
243
  ranges = []
@@ -247,8 +255,22 @@ module Dynamoid
247
255
  end
248
256
 
249
257
  Dynamoid.adapter.delete(source.table_name, ids, range_key: ranges.presence)
258
+ ids.size
259
+ end
260
+
261
+ # Destroys all the models by instantiating each model and calling
262
+ # +#destroy+ on it, running +destroy+ callbacks.
263
+ #
264
+ # Post.where(links_count: 2).destroy_all
265
+ #
266
+ # If called without criteria then it destroys all the models in a table.
267
+ #
268
+ # Post.destroy_all
269
+ #
270
+ # @return [Array<Dynamoid::Document>] the collection of models that were destroyed
271
+ def destroy_all
272
+ records.to_a.each(&:destroy)
250
273
  end
251
- alias destroy_all delete_all
252
274
 
253
275
  # Set the record limit.
254
276
  #
@@ -365,29 +387,47 @@ module Dynamoid
365
387
  self
366
388
  end
367
389
 
368
- # Force the index name to use for queries.
390
+ # Force a specific secondary index to use for queries or scans.
369
391
  #
370
- # By default allows the library to select the most appropriate index.
371
- # Sometimes you have more than one index which will fulfill your query's
372
- # needs. When this case occurs you may want to force an order. This occurs
373
- # when you are searching by hash key, but not specifying a range key.
392
+ # By default, Dynamoid automatically selects the most appropriate index
393
+ # using the following precedence:
374
394
  #
375
- # ```
395
+ # 1. Table partition key and sort key
396
+ # 2. Table partition key and Local Secondary Index (LSI) sort key
397
+ # 3. Global Secondary Index (GSI) with +projected_attributes: :all+ matching partition key and sort key
398
+ # 4. Table partition key alone
399
+ # 5. Global Secondary Index (GSI) with +projected_attributes: :all+ matching partition key alone
400
+ #
401
+ # Explicit index selection is useful in several scenarios:
402
+ # - When multiple secondary indexes match the query conditions and you want to ensure a specific index is used.
403
+ # - When querying an index with partial projection.
404
+ # - When scanning a sparse index to read only items containing the indexed attribute.
405
+ #
406
+ # When querying an index that projects only keys or a subset of attributes, Dynamoid
407
+ # loads only the projected fields. Non-projected attributes remain +nil+ on instantiated models.
408
+ #
409
+ # ```ruby
376
410
  # class Comment
377
411
  # include Dynamoid::Document
378
412
  #
379
413
  # table key: :post_id
380
- # range_key :author_id
414
+ # range :author_id
381
415
  #
382
416
  # field :post_date, :datetime
383
417
  #
384
- # global_secondary_index name: :time_sorted_comments, hash_key: :post_id, range_key: post_date, projected_attributes: :all
418
+ # global_secondary_index name: :time_sorted_comments, hash_key: :post_id, range_key: :post_date, projected_attributes: :all
385
419
  # end
386
420
  #
421
+ # # Force a specific index when querying
387
422
  # Comment.where(post_id: id).with_index(:time_sorted_comments).scan_index_forward(false)
423
+ #
424
+ # # Scan only items present in the index
425
+ # Comment.with_index(:time_sorted_comments).all
388
426
  # ```
389
427
  #
390
- # @return [Dynamoid::Criteria::Chain]
428
+ # @param index_name [Symbol, String] name of the secondary index declared on the model
429
+ # @raise [Dynamoid::Errors::InvalidIndex] if the index does not exist on the model
430
+ # @return [Dynamoid::Criteria::Chain] self
391
431
  def with_index(index_name)
392
432
  raise Dynamoid::Errors::InvalidIndex, "Unknown index #{index_name}" unless @source.find_index_by_name(index_name)
393
433
 
@@ -458,8 +498,12 @@ module Dynamoid
458
498
  # ```
459
499
  #
460
500
  # @return [Enumerator::Lazy]
461
- def find_by_pages(&block)
462
- pages.each(&block)
501
+ def find_by_pages
502
+ return to_enum(:find_by_pages).lazy unless block_given?
503
+
504
+ pages.each do |(models, options)|
505
+ yield models, options
506
+ end
463
507
  end
464
508
 
465
509
  # Select only specified fields.
@@ -12,6 +12,7 @@ module Dynamoid
12
12
  %i[
13
13
  where consistent all first last delete_all destroy_all each record_limit
14
14
  scan_limit batch start scan_index_forward find_by_pages project pluck
15
+ with_index
15
16
  ].each do |name|
16
17
  # Return a criteria chain in response to a method that will begin or end a chain. For more information,
17
18
  # see Dynamoid::Criteria::Chain.
@@ -60,8 +60,8 @@ module Dynamoid
60
60
 
61
61
  # @private
62
62
  def update(*)
63
- super.tap do
64
- clear_changes_information
63
+ super.tap do |status|
64
+ clear_changes_information if status
65
65
  end
66
66
  end
67
67
 
@@ -123,7 +123,7 @@ module Dynamoid
123
123
  #
124
124
  # @return [ActiveSupport::HashWithIndifferentAccess]
125
125
  def previous_changes
126
- @previously_changed ||= ActiveSupport::HashWithIndifferentAccess.new
126
+ @previous_changes ||= ActiveSupport::HashWithIndifferentAccess.new
127
127
  end
128
128
 
129
129
  # Returns a hash of the attributes with unsaved changes indicating their original
@@ -140,14 +140,14 @@ module Dynamoid
140
140
 
141
141
  # Clear all dirty data: current changes and previous changes.
142
142
  def clear_changes_information
143
- @previously_changed = ActiveSupport::HashWithIndifferentAccess.new
143
+ @previous_changes = ActiveSupport::HashWithIndifferentAccess.new
144
144
  @attributes_changed_by_setter = ActiveSupport::HashWithIndifferentAccess.new
145
145
  @attributes_from_database = HashWithIndifferentAccess.new(DeepDupper.dup_attributes(@attributes, self.class))
146
146
  end
147
147
 
148
148
  # Clears dirty data and moves +changes+ to +previous_changes+.
149
149
  def changes_applied
150
- @previously_changed = changes
150
+ @previous_changes = changes
151
151
  @attributes_changed_by_setter = ActiveSupport::HashWithIndifferentAccess.new
152
152
  @attributes_from_database = HashWithIndifferentAccess.new(DeepDupper.dup_attributes(@attributes, self.class))
153
153
  end
@@ -248,12 +248,8 @@ module Dynamoid
248
248
  def attribute_will_change!(name)
249
249
  return if attribute_changed?(name)
250
250
 
251
- begin
252
- value = read_attribute(name)
253
- value = value.clone if value.duplicable?
254
- rescue TypeError, NoMethodError
255
- end
256
-
251
+ value = read_attribute(name)
252
+ value = value.clone if value.duplicable?
257
253
  set_attribute_was(name, value)
258
254
  end
259
255
 
@@ -312,7 +308,7 @@ module Dynamoid
312
308
  # symbolized keys - wrap it into HashWithIndifferentAccess.
313
309
  value_wrapped = value.with_indifferent_access
314
310
  value_wrapped != value_from_database
315
- elsif !type_options[:type].is_a?(Class) || type_options[:comparable]
311
+ elsif !type_options[:type].is_a?(Module) || type_options[:comparable]
316
312
  # common case
317
313
  value != value_from_database
318
314
  else
@@ -344,7 +340,7 @@ module Dynamoid
344
340
  # IO objects (used for the binary type) cannot be duplicated as well.
345
341
  value
346
342
  when Array
347
- if of.is_a? Class
343
+ if of.is_a? Module
348
344
  # custom type
349
345
  value.map { |e| dup_attribute(e, type: of) }
350
346
  else
@@ -353,7 +349,7 @@ module Dynamoid
353
349
  when Set
354
350
  Set.new(value.map { |e| dup_attribute(e, type: of) })
355
351
  else
356
- if type.is_a? Class
352
+ if type.is_a? Module
357
353
  # custom type
358
354
  dump = Dumping.dump_field(value, type_options)
359
355
  Undumping.undump_field(dump.deep_dup, type_options)