Demonstrate TransactWriteItems and TransactGetItems.
(client)
| 401 | # --------------------------------------------------------------------------- |
| 402 | |
| 403 | def transaction_operations(client) -> None: |
| 404 | """Demonstrate TransactWriteItems and TransactGetItems.""" |
| 405 | section("Step 7: Transactions (TransactWriteItems + TransactGetItems)") |
| 406 | |
| 407 | # TransactWriteItems — atomically create a new user and their first order |
| 408 | client.transact_write_items( |
| 409 | TransactItems=[ |
| 410 | { |
| 411 | "Put": { |
| 412 | "TableName": USERS_TABLE, |
| 413 | "Item": { |
| 414 | "userId": {"S": "user-004"}, |
| 415 | "name": {"S": "Diana"}, |
| 416 | "email": {"S": "diana@example.com"}, |
| 417 | "age": {"N": "28"}, |
| 418 | }, |
| 419 | "ConditionExpression": "attribute_not_exists(userId)", |
| 420 | }, |
| 421 | }, |
| 422 | { |
| 423 | "Put": { |
| 424 | "TableName": ORDERS_TABLE, |
| 425 | "Item": { |
| 426 | "customerId": {"S": "user-004"}, |
| 427 | "orderId": {"S": "ord-401"}, |
| 428 | "orderDate": {"S": "2026-04-18"}, |
| 429 | "total": {"N": "99.99"}, |
| 430 | "status": {"S": "pending"}, |
| 431 | }, |
| 432 | }, |
| 433 | }, |
| 434 | ], |
| 435 | ) |
| 436 | print(" ✓ TransactWriteItems: created user-004 + order ord-401 atomically") |
| 437 | |
| 438 | # TransactGetItems — read both back in a single transaction |
| 439 | resp = client.transact_get_items( |
| 440 | TransactItems=[ |
| 441 | { |
| 442 | "Get": { |
| 443 | "TableName": USERS_TABLE, |
| 444 | "Key": {"userId": {"S": "user-004"}}, |
| 445 | }, |
| 446 | }, |
| 447 | { |
| 448 | "Get": { |
| 449 | "TableName": ORDERS_TABLE, |
| 450 | "Key": { |
| 451 | "customerId": {"S": "user-004"}, |
| 452 | "orderId": {"S": "ord-401"}, |
| 453 | }, |
| 454 | }, |
| 455 | }, |
| 456 | ], |
| 457 | ) |
| 458 | user = resp["Responses"][0]["Item"] |
| 459 | order = resp["Responses"][1]["Item"] |
| 460 | print(f" ✓ TransactGetItems: {user['name']['S']} has order {order['orderId']['S']} (${order['total']['N']})") |
no test coverage detected