Amazon DynamoDB · Update
Detect a change made since the read
Two people edit the same product: optimistic concurrency with a version attribute, in four scenarios: a create starts the version at 1, the first save wins, the second is told the item changed, and an update without the version.
Set up for this page
The scenarios build on the sample application: SampleContext.cs (the dbContext every sample is given); SampleOutput.cs (Step and Show, which print); SampleContext.Application.cs (dbContext.Service, the application's ARX service); SampleModel.cs (the DynamoDB layout and the schema catalog); SampleContext.Direct.cs (dbContext.Direct); DynamoDirectHelper.cs (the checks behind dbContext.Direct).
dbContext.Direct is the samples' own checking code on the plain driver, not part of ARX: leave it out of your application.
Before scenario 1 the sample runs this, so the service and the rows the scenarios use are there:
var schema = ArxSchemaCatalog.Create()
.Table("product", ArxIdColumn.Supplied<string>("sku"))
.Version("product", "row_version")
.Build();
var service = new ArxDynamoDbService(dbContext.Client, dbContext.Model, schema);1 A create starts the version at 1
Create a product: ARX writes its version, 1.
Already in scope: service (ArxDynamoDbService)
var product = new ArxEntity("product");
product["sku"] = "SKU-D271";
product["name"] = "Trail running shoe";
product["price"] = 129.90m;
await service.CreateAsync(product);
var read = await service.RetrieveAsync("product", "SKU-D271") ?? throw new InvalidOperationException("The product record isn't there.");
Console.WriteLine($"{read["name"]}, version {read["row_version"]}");Check it in the database
A PartiQL statement: run it in NoSQL Workbench, or with aws dynamodb execute-statement --statement, after the code has run.
SELECT "sku", "price", "row_version" FROM "product" WHERE "sku" = 'SKU-D271'Expect: 1 item, price 129.90, row_version 1.
2 The first save wins
Ana and Ben both read version 1; Ana saves first, with the version she read: written, now version 2.
Already in scope: service (ArxDynamoDbService)
var ana = await service.RetrieveAsync("product", "SKU-D271") ?? throw new InvalidOperationException("The product record isn't there.");
var change = new ArxEntity("product");
change["sku"] = "SKU-D271";
change["price"] = 119.90m;
change["row_version"] = ana["row_version"];
await service.UpdateAsync(change);
var read = await service.RetrieveAsync("product", "SKU-D271") ?? throw new InvalidOperationException("The product record isn't there.");
Console.WriteLine($"Ana's price {read["price"]}, version {read["row_version"]}");Check it in the database
A PartiQL statement: run it in NoSQL Workbench, or with aws dynamodb execute-statement --statement, after the code has run.
SELECT "price", "row_version" FROM "product" WHERE "sku" = 'SKU-D271'Expect: price 119.90, row_version 2.
3 The second save is told the item changed
Ben saves with the version 1 he read: ARX2004, nothing written; he reads again and saves with version 2.
Already in scope: service (ArxDynamoDbService)
var stale = new ArxEntity("product");
stale["sku"] = "SKU-D271";
stale["name"] = "Trail running shoe, wide";
stale["row_version"] = 1;
try
{
await service.UpdateAsync(stale);
}
catch (ArxException exception) when (exception.Code == ArxErrorCode.RecordChanged)
{
Console.WriteLine(exception.Message);
}
// Ben reads what is there now, and applies his change to it.
var now = await service.RetrieveAsync("product", "SKU-D271") ?? throw new InvalidOperationException("The product record isn't there.");
var retry = new ArxEntity("product");
retry["sku"] = "SKU-D271";
retry["name"] = "Trail running shoe, wide";
retry["row_version"] = now["row_version"];
await service.UpdateAsync(retry);
var read = await service.RetrieveAsync("product", "SKU-D271") ?? throw new InvalidOperationException("The product record isn't there.");
Console.WriteLine($"{read["name"]}, price {read["price"]}, version {read["row_version"]}");Check it in the database
A PartiQL statement: run it in NoSQL Workbench, or with aws dynamodb execute-statement --statement, after the code has run.
SELECT "name", "price", "row_version" FROM "product" WHERE "sku" = 'SKU-D271'Expect: Trail running shoe, wide; price 119.90 (Ana's, kept); row_version 3.
4 An update without the version: the last writer wins
An update without the version isn't checked: it is written whatever the item's version, which still goes up.
Already in scope: service (ArxDynamoDbService)
var blind = new ArxEntity("product");
blind["sku"] = "SKU-D271";
blind["price"] = 99.90m;
await service.UpdateAsync(blind);
var read = await service.RetrieveAsync("product", "SKU-D271") ?? throw new InvalidOperationException("The product record isn't there.");
Console.WriteLine($"price {read["price"]}, version {read["row_version"]}");Check it in the database
A PartiQL statement: run it in NoSQL Workbench, or with aws dynamodb execute-statement --statement, after the code has run.
SELECT "price", "row_version" FROM "product" WHERE "sku" = 'SKU-D271'Expect: price 99.90, row_version 4.
Good to know
Declare the version attribute in the schema catalog: .Version("product", "row_version"). A create writes 1 when the entity gives none. An update or a delete whose entity carries the version it read is written only if the item still has it, and an update adds one; otherwise it is ARX2004 RecordChanged and nothing is written (one round trip: the failed write returns the item, so a missing item is still ARX2002). An update without the version isn't checked: the last writer wins, though the version still goes up. So read the version with the item, and send it back with the change. A move to a new key (AllowKeyChange) checks the version too.
Run the complete sample
The code above comes from one program, built in a fresh project and run against the database. To run it yourself, here is every file and step.
The program, its files and how to run it
Run it locally
- .NET SDK: .NET SDK 10.0.100 or later 10.0.x (target
net10.0). - Create the project:
Terminal dotnet new console -n ArxSample -f net10.0 cd ArxSample - Install the packages:
Terminal dotnet add package ARX.SDK.DynamoDb --version 1.0.0-rc.1 - Database: a Amazon DynamoDB, or DynamoDB Local for development (tested with DynamoDB Local 2.5.2) database with the sample schema.
- Configuration: set
ARX_SAMPLES_DYNAMODBto its connection string. Nothing is hard-coded. - Source code: add the files of the sample application this sample uses (
SampleContext.cs,SampleOutput.cs,SampleContext.Application.cs,SampleModel.cs,SampleContext.Direct.cs,DynamoDirectHelper.cs), then replaceProgram.csand add the other file below, with the file names shown. - Run it:
Terminal dotnet run - Expected output: below.
The files
Runs the sample. Generated for this page; it reads the connection string from the environment and first remakes the sample database from sample-schema.json.
using ArxSamples.DynamoDb;
using ArxSamples.DynamoDb.Operations.Update.RealCases;
// The connection string comes from the environment, never from the code (see "Configure the connection").
var connectionString = Environment.GetEnvironmentVariable("ARX_SAMPLES_DYNAMODB")
?? throw new InvalidOperationException("Set the ARX_SAMPLES_DYNAMODB environment variable to your Amazon DynamoDB connection string.");
var dbContext = new SampleContext(connectionString);
// Every run starts from the sample data: this deletes and makes again what sample-schema.json lists
// (save the file in the project folder, see Get started).
await dbContext.Direct.ResetAsync();
await new RealCase2_DetectAChangeMadeSinceTheRead().RunAsync(dbContext);
The sample, as it is in the repository.
using ARX.SDK;
using ARX.SDK.DynamoDb.Services;
using ARX.SDK.Services;
using static ArxSamples.DynamoDb.SampleOutput;
namespace ArxSamples.DynamoDb.Operations.Update.RealCases;
/// <summary>
/// Two people edit the same product: optimistic concurrency with a version attribute, in four scenarios: a create starts
/// the version at 1, the first save wins, the second is told the item changed, and an update without the version.
/// </summary>
/// <remarks>
/// Declare the version attribute in the schema catalog: <c>.Version("product", "row_version")</c>. A create writes 1 when
/// the entity gives none. An update or a delete whose entity carries the version it read is written only if the item still
/// has it, and an update adds one; otherwise it is ARX2004 RecordChanged and nothing is written (one round trip: the
/// failed write returns the item, so a missing item is still ARX2002). An update without the version isn't checked: the
/// last writer wins, though the version still goes up. So read the version with the item, and send it back with the change.
/// A move to a new key (AllowKeyChange) checks the version too.
/// </remarks>
public sealed class RealCase2_DetectAChangeMadeSinceTheRead : ISample
{
public string Name => "update-real-2-detect-a-change-made-since-the-read";
public string Title => "Detect a change made since the read";
public async Task RunAsync(SampleContext dbContext)
{
// The version attribute is declared once, with the table.
var schema = ArxSchemaCatalog.Create()
.Table("product", ArxIdColumn.Supplied<string>("sku"))
.Version("product", "row_version")
.Build();
var service = new ArxDynamoDbService(dbContext.Client, dbContext.Model, schema);
await Scenario1_CreateStartsAtOneAsync(service);
await Scenario2_TheFirstSaveWinsAsync(service);
await Scenario3_TheSecondIsToldAsync(service);
await Scenario4_WithoutTheVersionAsync(service);
}
/// <summary>1. Create a product: ARX writes its version, 1.</summary>
private static async Task Scenario1_CreateStartsAtOneAsync(ArxDynamoDbService service)
{
Step("1. A create starts the version at 1");
var product = new ArxEntity("product");
product["sku"] = "SKU-D271";
product["name"] = "Trail running shoe";
product["price"] = 129.90m;
await service.CreateAsync(product);
var read = await service.RetrieveAsync("product", "SKU-D271") ?? throw new InvalidOperationException("The product record isn't there.");
Show($"{read["name"]}, version {read["row_version"]}");
/* ===========================================================
* [DIRECT QUERY CHECK]
* -----------------------------------------------------------
* SELECT "sku", "price", "row_version" FROM "product" WHERE "sku" = 'SKU-D271'
* -- Expect: 1 item, price 129.90, row_version 1.
* ===========================================================
*/
}
/// <summary>2. Ana and Ben both read version 1; Ana saves first, with the version she read: written, now version 2.</summary>
private static async Task Scenario2_TheFirstSaveWinsAsync(ArxDynamoDbService service)
{
Step("2. The first save wins");
var ana = await service.RetrieveAsync("product", "SKU-D271") ?? throw new InvalidOperationException("The product record isn't there.");
var change = new ArxEntity("product");
change["sku"] = "SKU-D271";
change["price"] = 119.90m;
change["row_version"] = ana["row_version"];
await service.UpdateAsync(change);
var read = await service.RetrieveAsync("product", "SKU-D271") ?? throw new InvalidOperationException("The product record isn't there.");
Show($"Ana's price {read["price"]}, version {read["row_version"]}");
/* ===========================================================
* [DIRECT QUERY CHECK]
* -----------------------------------------------------------
* SELECT "price", "row_version" FROM "product" WHERE "sku" = 'SKU-D271'
* -- Expect: price 119.90, row_version 2.
* ===========================================================
*/
}
/// <summary>3. Ben saves with the version 1 he read: ARX2004, nothing written; he reads again and saves with version 2.</summary>
private static async Task Scenario3_TheSecondIsToldAsync(ArxDynamoDbService service)
{
Step("3. The second save is told the item changed");
var stale = new ArxEntity("product");
stale["sku"] = "SKU-D271";
stale["name"] = "Trail running shoe, wide";
stale["row_version"] = 1;
try
{
await service.UpdateAsync(stale);
}
catch (ArxException exception) when (exception.Code == ArxErrorCode.RecordChanged)
{
ShowError(exception);
}
// Ben reads what is there now, and applies his change to it.
var now = await service.RetrieveAsync("product", "SKU-D271") ?? throw new InvalidOperationException("The product record isn't there.");
var retry = new ArxEntity("product");
retry["sku"] = "SKU-D271";
retry["name"] = "Trail running shoe, wide";
retry["row_version"] = now["row_version"];
await service.UpdateAsync(retry);
var read = await service.RetrieveAsync("product", "SKU-D271") ?? throw new InvalidOperationException("The product record isn't there.");
Show($"{read["name"]}, price {read["price"]}, version {read["row_version"]}");
/* ===========================================================
* [DIRECT QUERY CHECK]
* -----------------------------------------------------------
* SELECT "name", "price", "row_version" FROM "product" WHERE "sku" = 'SKU-D271'
* -- Expect: Trail running shoe, wide; price 119.90 (Ana's, kept); row_version 3.
* ===========================================================
*/
}
/// <summary>4. An update without the version isn't checked: it is written whatever the item's version, which still goes up.</summary>
private static async Task Scenario4_WithoutTheVersionAsync(ArxDynamoDbService service)
{
Step("4. An update without the version: the last writer wins");
var blind = new ArxEntity("product");
blind["sku"] = "SKU-D271";
blind["price"] = 99.90m;
await service.UpdateAsync(blind);
var read = await service.RetrieveAsync("product", "SKU-D271") ?? throw new InvalidOperationException("The product record isn't there.");
Show($"price {read["price"]}, version {read["row_version"]}");
/* ===========================================================
* [DIRECT QUERY CHECK]
* -----------------------------------------------------------
* SELECT "price", "row_version" FROM "product" WHERE "sku" = 'SKU-D271'
* -- Expect: price 99.90, row_version 4.
* ===========================================================
*/
}
}
Expected output
What dotnet run printed when the sample was verified, on a freshly created sample schema. Ids differ when the tables already hold rows.
> 1. A create starts the version at 1
Trail running shoe, version 1
> 2. The first save wins
Ana's price 119.90, version 2
> 3. The second save is told the item changed
caught ArxDatabaseException: ARX2004 RecordChanged: Update of 'product': the item of 'product' was changed since it was read: its 'row_version' is 2, not 1. Nothing was written: read it again and apply the change to what is there now.
Trail running shoe, wide, price 119.90, version 3
> 4. An update without the version: the last writer wins
price 99.90, version 4