From f8fbce86c82bd5045fc3e223d18c29400e186e6d Mon Sep 17 00:00:00 2001 From: Andrii Konchyn Date: Sat, 28 Nov 2026 19:19:25 +0200 Subject: [PATCH 1/3] Add .find_by_partiql finder method --- lib/dynamoid/finders.rb | 44 +++++++++++++ spec/dynamoid/finders_spec.rb | 119 ++++++++++++++++++++++++++++++++++ 2 files changed, 163 insertions(+) diff --git a/lib/dynamoid/finders.rb b/lib/dynamoid/finders.rb index 4aa38a39..094e8869 100644 --- a/lib/dynamoid/finders.rb +++ b/lib/dynamoid/finders.rb @@ -57,6 +57,50 @@ def find(*ids, **options) end end + # Find objects by executing a PartiQL +SELECT+ statement. + # + # Executes the given PartiQL statement against DynamoDB and instantiates + # matching model instances, running +after_initialize+ and +after_find+ + # callbacks. + # + # The table name in the statement must equal DynamoDB's table name (such + # as +User.table_name+). Bind parameter values are passed directly to + # DynamoDB without type casting or serialization (for example, +:datetime+ + # and +:date+ values must be passed in their underlying storage format, + # such as numeric Unix epoch timestamps or ISO 8601 strings). + # + # Reads are eventually consistent by default. Pass +consistent_read: true+ + # to perform a strongly consistent read. + # + # @param statement [String] PartiQL statement + # @param parameters [Array] a list of bind parameters (optional) + # @param options [Hash] (optional) + # @option options [true|false] :consistent_read perform a strongly consistent read + # @return [Array] matching model instances + # + # @example Find all items + # User.find_by_partiql("SELECT * FROM #{User.table_name}") + # + # @example Find items with bind parameters + # User.find_by_partiql("SELECT * FROM #{User.table_name} WHERE name = ?", ['Alice']) + # + # @example Perform a strongly consistent read + # User.find_by_partiql("SELECT * FROM #{User.table_name} WHERE id = ?", ['101'], consistent_read: true) + def find_by_partiql(statement, parameters = [], options = {}) + if parameters.is_a?(Hash) && options.empty? + options = parameters + parameters = [] + end + + items = Dynamoid.adapter.execute(statement, parameters, options.slice(:consistent_read)) + + items.map do |item| + model = from_database(item) + model.run_callbacks :find + model + end.to_a + end + # Find several models at once. # # Returns objects found by the given array of ids, either hash keys, or diff --git a/spec/dynamoid/finders_spec.rb b/spec/dynamoid/finders_spec.rb index 73783712..547849f5 100644 --- a/spec/dynamoid/finders_spec.rb +++ b/spec/dynamoid/finders_spec.rb @@ -798,4 +798,123 @@ def time_to_decimal(time) end end end + + describe '.find_by_partiql' do + let(:klass) do + new_class(class_name: 'Document') do + field :name + field :age, :integer + end + end + + it 'finds models matching a PartiQL statement' do + obj1 = klass.create!(name: 'Alice', age: 30) + obj2 = klass.create!(name: 'Bob', age: 25) + + results = klass.find_by_partiql("SELECT * FROM \"#{klass.table_name}\"") + + expect(results).to be_an(Array) + expect(results).to contain_exactly(obj1, obj2) + end + + it 'accepts bind parameters as an array' do + obj1 = klass.create!(name: 'Alice', age: 30) + klass.create!(name: 'Bob', age: 25) + + results = klass.find_by_partiql("SELECT * FROM \"#{klass.table_name}\" WHERE name = ?", ['Alice']) + + expect(results).to eql([obj1]) + end + + it 'returns an empty array when nothing matches' do + klass.create_table + + results = klass.find_by_partiql("SELECT * FROM \"#{klass.table_name}\" WHERE name = ?", ['Nobody']) + + expect(results).to eql([]) + end + + it 'returns persisted and clean models' do + klass.create!(name: 'Alice', age: 30) + + model = klass.find_by_partiql("SELECT * FROM \"#{klass.table_name}\"").first + + expect(model).to be_persisted + expect(model).not_to be_changed + end + + it 'undumps attribute values according to declared field types' do + klass_with_date = new_class do + field :published_on, :date + field :count, :integer + end + obj = klass_with_date.create!(published_on: Date.new(2026, 1, 15), count: 42) + + model = klass_with_date.find_by_partiql("SELECT * FROM \"#{klass_with_date.table_name}\"").first + + expect(model.published_on).to eql(Date.new(2026, 1, 15)) + expect(model.count).to eql(42) + expect(model).to eql(obj) + end + + it 'ignores undeclared attributes without raising exceptions' do + klass.create_table + Dynamoid.adapter.put_item(klass.table_name, id: '1', name: 'Alice', extra: 'ignored') + + model = klass.find_by_partiql("SELECT * FROM \"#{klass.table_name}\"").first + + expect(model.id).to eql('1') + expect(model.name).to eql('Alice') + end + + it 'accepts :consistent_read option with parameters' do + klass.create_table + + expect { + klass.find_by_partiql("SELECT * FROM \"#{klass.table_name}\" WHERE id = ?", ['1'], consistent_read: true) + }.to send_request_matching(:ExecuteStatement, { ConsistentRead: true }) + + expect { + klass.find_by_partiql("SELECT * FROM \"#{klass.table_name}\" WHERE id = ?", ['1'], consistent_read: false) + }.to send_request_matching(:ExecuteStatement, { ConsistentRead: false }) + end + + it 'accepts :consistent_read option without parameters' do + klass.create_table + + expect { + klass.find_by_partiql("SELECT * FROM \"#{klass.table_name}\"", consistent_read: true) + }.to send_request_matching(:ExecuteStatement, { ConsistentRead: true }) + end + + it 'supports STI subclasses' do + car = Car.create!(name: 'Sedan') + submarine = NuclearSubmarine.create!(name: 'Nautilus') + + results = Vehicle.find_by_partiql("SELECT * FROM \"#{Vehicle.table_name}\"") + + expect(results).to contain_exactly(car, submarine) + expect(results.find { |m| m.id == car.id }).to be_a(Car) + expect(results.find { |m| m.id == submarine.id }).to be_a(NuclearSubmarine) + end + + describe 'callbacks' do + before do + ScratchPad.record [] + end + + it 'runs after_initialize and after_find callbacks in proper order' do + klass_with_callback = new_class do + after_initialize { ScratchPad << 'run after_initialize' } + after_find { ScratchPad << 'run after_find' } + end + klass_with_callback.create! + + ScratchPad.record [] + klass_with_callback.find_by_partiql("SELECT * FROM \"#{klass_with_callback.table_name}\"") + + expect(ScratchPad.recorded).to eql(['run after_initialize', 'run after_find']) + end + end + end end From 6d5bc63ce59f27c18b57cd16032d788cab66e7b7 Mon Sep 17 00:00:00 2001 From: Andrii Konchyn Date: Sat, 28 Nov 2026 19:40:42 +0200 Subject: [PATCH 2/3] Add .execute_partiql persistence method --- lib/dynamoid/persistence.rb | 40 ++++++++++ .../persistence/execute_partiql_spec.rb | 74 +++++++++++++++++++ spec/dynamoid/persistence_spec.rb | 9 +++ 3 files changed, 123 insertions(+) create mode 100644 spec/dynamoid/persistence/execute_partiql_spec.rb diff --git a/lib/dynamoid/persistence.rb b/lib/dynamoid/persistence.rb index 5623e94b..3d45ce5f 100644 --- a/lib/dynamoid/persistence.rb +++ b/lib/dynamoid/persistence.rb @@ -551,6 +551,46 @@ def delete(*ids) nil end + + # Execute a modifying PartiQL statement (+INSERT+, +UPDATE+, or +DELETE+). + # + # Executes the given PartiQL statement directly against DynamoDB and + # returns +nil+. + # + # Modifications bypass Dynamoid's model lifecycle: validations, callbacks, + # dirty tracking, automatic timestamps, and optimistic locking are + # skipped. Table names in the statement must match the underlying DynamoDB + # table name (such as +User.table_name+). Bind parameter values are passed + # directly to DynamoDB without type casting or conversion to DynamoDB's + # underlying storage format (for example, +:datetime+ and +:date+ values + # must be passed in their stored representation, such as numeric Unix + # epoch timestamps or ISO 8601 strings). + # + # @param statement [String] PartiQL statement + # @param parameters [Array] a list of bind parameters (optional) + # @return nil + # + # @example Insert an item + # User.execute_partiql( + # "INSERT INTO \"#{User.table_name}\" VALUE { 'id': ?, 'name': ?, 'age': ? }", + # ['101', 'Alice', 28] + # ) + # + # @example Update an item + # User.execute_partiql( + # "UPDATE \"#{User.table_name}\" SET age = ? WHERE id = ?", + # [29, '101'] + # ) + # + # @example Delete an item + # User.execute_partiql( + # "DELETE FROM \"#{User.table_name}\" WHERE id = ?", + # ['101'] + # ) + def execute_partiql(statement, parameters = []) + Dynamoid.adapter.execute(statement, parameters) + nil + end end # Update document timestamps. diff --git a/spec/dynamoid/persistence/execute_partiql_spec.rb b/spec/dynamoid/persistence/execute_partiql_spec.rb new file mode 100644 index 00000000..4c4ab665 --- /dev/null +++ b/spec/dynamoid/persistence/execute_partiql_spec.rb @@ -0,0 +1,74 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe Dynamoid::Persistence do + describe '.execute_partiql' do + let(:klass) do + new_class(class_name: 'Document') do + field :name + field :age, :integer + end + end + + it 'executes an INSERT statement and returns nil' do + klass.create_table + + result = klass.execute_partiql( + "INSERT INTO \"#{klass.table_name}\" VALUE { 'id': '1', 'name': 'Alice', 'age': 30 }" + ) + + expect(result).to be_nil + loaded = klass.find('1') + expect(loaded.name).to eql('Alice') + expect(loaded.age).to eql(30) + end + + it 'executes an UPDATE statement and returns nil' do + obj = klass.create!(name: 'Alice', age: 30) + + result = klass.execute_partiql( + "UPDATE \"#{klass.table_name}\" SET name = 'Bob' WHERE id = '#{obj.id}'" + ) + + expect(result).to be_nil + expect(obj.reload.name).to eql('Bob') + end + + it 'executes a DELETE statement and returns nil' do + obj = klass.create!(name: 'Alice', age: 30) + + result = klass.execute_partiql( + "DELETE FROM \"#{klass.table_name}\" WHERE id = '#{obj.id}'" + ) + + expect(result).to be_nil + expect(klass.exists?(obj.id)).to be(false) + end + + it 'accepts bind parameters as an array' do + obj = klass.create!(name: 'Alice', age: 30) + + klass.execute_partiql( + "UPDATE \"#{klass.table_name}\" SET name = ?, age = ? WHERE id = ?", + ['Bob', 35, obj.id] + ) + + reloaded = obj.reload + expect(reloaded.name).to eql('Bob') + expect(reloaded.age).to eql(35) + end + + it 'returns nil when WHERE condition evaluates to false' do + obj = klass.create!(name: 'Alice', age: 30) + + result = klass.execute_partiql( + "UPDATE \"#{klass.table_name}\" SET name = ? WHERE id = ? AND age = ?", + ['Bob', obj.id, 99] + ) + + expect(result).to be_nil + expect(obj.reload.name).to eql('Alice') + end + end +end diff --git a/spec/dynamoid/persistence_spec.rb b/spec/dynamoid/persistence_spec.rb index a4b84745..a01749fd 100644 --- a/spec/dynamoid/persistence_spec.rb +++ b/spec/dynamoid/persistence_spec.rb @@ -110,6 +110,15 @@ klass.delete(instance.id) expect { klass.find(instance.id) }.to raise_error(Dynamoid::Errors::RecordNotFound) end + + it 'supports .execute_partiql' do + klass = new_class do + field :name + end + instance = klass.create!(name: 'Alex') + klass.execute_partiql("UPDATE \"#{klass.table_name}\" SET name = ? WHERE id = ?", ['Bob', instance.id]) + expect(klass.find(instance.id).name).to eq 'Bob' + end end describe 'instance methods' do From c66334c2943ce9efdf897aeb8cfa5177c841082e Mon Sep 17 00:00:00 2001 From: Andrii Konchyn Date: Sat, 28 Nov 2026 20:10:53 +0200 Subject: [PATCH 3/3] Document .find_by_partiql and .execute_partiql in guides Replace `Dynamoid.adapter.execute` examples with the new public `find_by_partiql` and `execute_partiql` methods in the Query Interface and Persistence guides, and clarify eager loading, singleton `UPDATE`/`DELETE` behavior, exact table names, and parameter formatting. --- doc/working_with_data/persistence.md | 18 ++++++++++-------- doc/working_with_data/query_interface.md | 15 +++++---------- 2 files changed, 15 insertions(+), 18 deletions(-) diff --git a/doc/working_with_data/persistence.md b/doc/working_with_data/persistence.md index 31817dad..fbc85564 100644 --- a/doc/working_with_data/persistence.md +++ b/doc/working_with_data/persistence.md @@ -350,36 +350,38 @@ user.update_attributes(lock_version: nil) ## Modifying Items with PartiQL -DynamoDB supports [PartiQL](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.html), a SQL-compatible query language that allows inserting, updating, and deleting items using familiar SQL statements through `Dynamoid.adapter.execute`. +DynamoDB supports [PartiQL](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.html), a SQL-compatible query language that allows inserting, updating, and deleting items using familiar SQL statements. Use `execute_partiql` to execute modifying statements directly against DynamoDB and return `nil`. To insert a new item, execute an `INSERT` statement: ```ruby -Dynamoid.adapter.execute( +User.execute_partiql( "INSERT INTO #{User.table_name} VALUE { 'id': ?, 'name': ?, 'age': ? }", ['3a9f7216-4726-4aea-9fbc-8554ae9292cb', 'Alex', 28] -) +) # => nil ``` To modify attributes on an existing item, execute an `UPDATE` statement: ```ruby -Dynamoid.adapter.execute( +User.execute_partiql( "UPDATE #{User.table_name} SET age = ? WHERE id = ?", [29, '3a9f7216-4726-4aea-9fbc-8554ae9292cb'] -) +) # => nil ``` To remove an item by its primary key, execute a `DELETE` statement: ```ruby -Dynamoid.adapter.execute( +User.execute_partiql( "DELETE FROM #{User.table_name} WHERE id = ?", ['3a9f7216-4726-4aea-9fbc-8554ae9292cb'] -) +) # => nil ``` +Unlike standard SQL, DynamoDB's PartiQL `UPDATE` and `DELETE` are singleton operations: each statement operates on a single item and requires specifying its full primary key in the `WHERE` clause (partition key, and sort key if the table has a composite primary key). + > [!NOTE] -> Modifications executed via `Dynamoid.adapter.execute` bypass Dynamoid's model lifecycle—validations, callbacks, dirty tracking, automatic timestamps, and optimistic locking are skipped. In addition, Dynamoid does not type-cast parameter values; non-native types (such as `:datetime` or `:date`) must be manually converted to their underlying storage format (such as numeric Unix epoch timestamps or ISO 8601 strings). In PartiQL statements, table names must match the underlying DynamoDB table name (such as `User.table_name`). +> Dynamoid does not type-cast bind parameter values or convert them to DynamoDB's underlying storage format; non-native types (such as `:datetime` or `:date`) must be passed in their stored representation (such as numeric Unix epoch timestamps or ISO 8601 strings). In PartiQL statements, the table name must equal DynamoDB's table name (such as `User.table_name`). {{#include ../_includes/feedback.md}} diff --git a/doc/working_with_data/query_interface.md b/doc/working_with_data/query_interface.md index c5357f41..c2a1cd6f 100644 --- a/doc/working_with_data/query_interface.md +++ b/doc/working_with_data/query_interface.md @@ -460,25 +460,20 @@ pages = User.where(active: true).batch(25).find_by_pages ## Finding Items with PartiQL -DynamoDB supports [PartiQL](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.html), a SQL-compatible query language that allows reading and writing items using familiar SQL statements. You can execute raw `SELECT` queries through the adapter using `Dynamoid.adapter.execute`: +DynamoDB supports [PartiQL](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.html), a SQL-compatible query language that allows reading and writing items using familiar SQL statements. Use `find_by_partiql` to execute raw `SELECT` statements and return instantiated models: ```ruby -results = Dynamoid.adapter.execute( +users = User.find_by_partiql( "SELECT * FROM #{User.table_name} WHERE id = ?", ['3a9f7216-4726-4aea-9fbc-8554ae9292cb'] ) -# => [{ id: "3a9f7216...", name: "Alice", active: true }] - -results.each do |item| - puts item[:name] -end -# Alice +# => [#] ``` -For large result sets, `Dynamoid.adapter.execute` automatically handles pagination and streams items lazily as you iterate. +Unlike `all` and `each` (which stream items lazily on demand), `find_by_partiql` eagerly fetches all matching items across paginated DynamoDB responses and returns an `Array` of instantiated models (converting stored attribute values back to their declared field types and running `after_initialize` and `after_find` callbacks). > [!NOTE] -> Queries executed via `Dynamoid.adapter.execute` return plain Ruby hashes with symbolized keys rather than instantiated `Dynamoid::Document` model instances. In addition, Dynamoid does not type-cast parameter values; non-native types (such as `:datetime` or `:date`) must be manually converted to their underlying storage format (such as numeric Unix epoch timestamps or ISO 8601 strings). In PartiQL statements, table names must match the underlying DynamoDB table name (such as `User.table_name`). +> Dynamoid does not type-cast bind parameter values or convert them to DynamoDB's underlying storage format; non-native types (such as `:datetime` or `:date`) must be passed in their stored representation (such as numeric Unix epoch timestamps or ISO 8601 strings). In PartiQL statements, the table name must equal DynamoDB's table name (such as `User.table_name`). {{#include ../_includes/feedback.md}}