Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 10 additions & 8 deletions doc/working_with_data/persistence.md
Original file line number Diff line number Diff line change
Expand Up @@ -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}}
15 changes: 5 additions & 10 deletions doc/working_with_data/query_interface.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
# => [#<User id: "3a9f7216...", name: "Alice", active: true>]
```

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}}

44 changes: 44 additions & 0 deletions lib/dynamoid/finders.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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<Dynamoid::Document>] 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
Expand Down
40 changes: 40 additions & 0 deletions lib/dynamoid/persistence.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
119 changes: 119 additions & 0 deletions spec/dynamoid/finders_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
74 changes: 74 additions & 0 deletions spec/dynamoid/persistence/execute_partiql_spec.rb
Original file line number Diff line number Diff line change
@@ -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
9 changes: 9 additions & 0 deletions spec/dynamoid/persistence_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading