第 5 步:修改分类账中的文档 - 亚马逊 Quantum Ledger 数据库(亚马逊QLDB)

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

第 5 步:修改分类账中的文档

重要

终止支持通知:现有客户将能够使用亚马逊,QLDB直到 2025 年 7 月 31 日终止支持。有关更多详细信息,请参阅将亚马逊QLDB账本迁移到亚马逊 Aurora Postgr SQL e。

既然您有了要处理的数据,就可以开始在 Amazon 中更改vehicle-registration账本中的文档QLDB了。在此步骤中,以下代码示例演示了如何运行数据操作语言 (DML) 语句。这些声明更新一辆车的主要车主,并为另一辆车添加了次要车主。

修改文档
  1. 编译并运行以下程序 (TransferVehicleOwnership.java),以更新账本VIN1N4AL11D75C109151中的车辆主要所有者。

    2.x
    /* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: MIT-0 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package software.amazon.qldb.tutorial; import com.amazon.ion.IonReader; import com.amazon.ion.IonStruct; import com.amazon.ion.IonValue; import com.amazon.ion.system.IonReaderBuilder; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.qldb.Result; import software.amazon.qldb.TransactionExecutor; import software.amazon.qldb.tutorial.model.Owner; import software.amazon.qldb.tutorial.model.Person; import software.amazon.qldb.tutorial.model.SampleData; /** * Find primary owner for a particular vehicle's VIN. * Transfer to another primary owner for a particular vehicle's VIN. * * This code expects that you have AWS credentials setup per: * http://docs.aws.amazon.com/java-sdk/latest/developer-guide/setup-credentials.html */ public final class TransferVehicleOwnership { public static final Logger log = LoggerFactory.getLogger(TransferVehicleOwnership.class); private TransferVehicleOwnership() { } /** * Query a driver's information using the given ID. * * @param txn * The {@link TransactionExecutor} for lambda execute. * @param documentId * The unique ID of a document in the Person table. * @return a {@link Person} object. * @throws IllegalStateException if failed to convert parameter into {@link IonValue}. */ public static Person findPersonFromDocumentId(final TransactionExecutor txn, final String documentId) { try { log.info("Finding person for documentId: {}...", documentId); final String query = "SELECT p.* FROM Person AS p BY pid WHERE pid = ?"; Result result = txn.execute(query, Constants.MAPPER.writeValueAsIonValue(documentId)); if (result.isEmpty()) { throw new IllegalStateException("Unable to find person with ID: " + documentId); } return Constants.MAPPER.readValue(result.iterator().next(), Person.class); } catch (IOException ioe) { throw new IllegalStateException(ioe); } } /** * Find the primary owner for the given VIN. * * @param txn * The {@link TransactionExecutor} for lambda execute. * @param vin * Unique VIN for a vehicle. * @return a {@link Person} object. * @throws IllegalStateException if failed to convert parameter into {@link IonValue}. */ public static Person findPrimaryOwnerForVehicle(final TransactionExecutor txn, final String vin) { try { log.info("Finding primary owner for vehicle with Vin: {}...", vin); final String query = "SELECT Owners.PrimaryOwner.PersonId FROM VehicleRegistration AS v WHERE v.VIN = ?"; final List<IonValue> parameters = Collections.singletonList(Constants.MAPPER.writeValueAsIonValue(vin)); Result result = txn.execute(query, parameters); final List<IonStruct> documents = ScanTable.toIonStructs(result); ScanTable.printDocuments(documents); if (documents.isEmpty()) { throw new IllegalStateException("Unable to find registrations with VIN: " + vin); } final IonReader reader = IonReaderBuilder.standard().build(documents.get(0)); final String personId = Constants.MAPPER.readValue(reader, LinkedHashMap.class).get("PersonId").toString(); return findPersonFromDocumentId(txn, personId); } catch (IOException ioe) { throw new IllegalStateException(ioe); } } /** * Update the primary owner for a vehicle registration with the given documentId. * * @param txn * The {@link TransactionExecutor} for lambda execute. * @param vin * Unique VIN for a vehicle. * @param documentId * New PersonId for the primary owner. * @throws IllegalStateException if no vehicle registration was found using the given document ID and VIN, or if failed * to convert parameters into {@link IonValue}. */ public static void updateVehicleRegistration(final TransactionExecutor txn, final String vin, final String documentId) { try { log.info("Updating primary owner for vehicle with Vin: {}...", vin); final String query = "UPDATE VehicleRegistration AS v SET v.Owners.PrimaryOwner = ? WHERE v.VIN = ?"; final List<IonValue> parameters = new ArrayList<>(); parameters.add(Constants.MAPPER.writeValueAsIonValue(new Owner(documentId))); parameters.add(Constants.MAPPER.writeValueAsIonValue(vin)); Result result = txn.execute(query, parameters); ScanTable.printDocuments(result); if (result.isEmpty()) { throw new IllegalStateException("Unable to transfer vehicle, could not find registration."); } else { log.info("Successfully transferred vehicle with VIN '{}' to new owner.", vin); } } catch (IOException ioe) { throw new IllegalStateException(ioe); } } public static void main(final String... args) { final String vin = SampleData.VEHICLES.get(0).getVin(); final String primaryOwnerGovId = SampleData.PEOPLE.get(0).getGovId(); final String newPrimaryOwnerGovId = SampleData.PEOPLE.get(1).getGovId(); ConnectToLedger.getDriver().execute(txn -> { final Person primaryOwner = findPrimaryOwnerForVehicle(txn, vin); if (!primaryOwner.getGovId().equals(primaryOwnerGovId)) { // Verify the primary owner. throw new IllegalStateException("Incorrect primary owner identified for vehicle, unable to transfer."); } final String newOwner = Person.getDocumentIdByGovId(txn, newPrimaryOwnerGovId); updateVehicleRegistration(txn, vin, newOwner); }); log.info("Successfully transferred vehicle ownership!"); } }
    1.x
    /* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: MIT-0 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package software.amazon.qldb.tutorial; import com.amazon.ion.IonReader; import com.amazon.ion.IonStruct; import com.amazon.ion.IonValue; import com.amazon.ion.system.IonReaderBuilder; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.qldb.Result; import software.amazon.qldb.TransactionExecutor; import software.amazon.qldb.tutorial.model.Owner; import software.amazon.qldb.tutorial.model.Person; import software.amazon.qldb.tutorial.model.SampleData; /** * Find primary owner for a particular vehicle's VIN. * Transfer to another primary owner for a particular vehicle's VIN. * * This code expects that you have AWS credentials setup per: * http://docs.aws.amazon.com/java-sdk/latest/developer-guide/setup-credentials.html */ public final class TransferVehicleOwnership { public static final Logger log = LoggerFactory.getLogger(TransferVehicleOwnership.class); private TransferVehicleOwnership() { } /** * Query a driver's information using the given ID. * * @param txn * The {@link TransactionExecutor} for lambda execute. * @param documentId * The unique ID of a document in the Person table. * @return a {@link Person} object. * @throws IllegalStateException if failed to convert parameter into {@link IonValue}. */ public static Person findPersonFromDocumentId(final TransactionExecutor txn, final String documentId) { try { log.info("Finding person for documentId: {}...", documentId); final String query = "SELECT p.* FROM Person AS p BY pid WHERE pid = ?"; Result result = txn.execute(query, Constants.MAPPER.writeValueAsIonValue(documentId)); if (result.isEmpty()) { throw new IllegalStateException("Unable to find person with ID: " + documentId); } return Constants.MAPPER.readValue(result.iterator().next(), Person.class); } catch (IOException ioe) { throw new IllegalStateException(ioe); } } /** * Find the primary owner for the given VIN. * * @param txn * The {@link TransactionExecutor} for lambda execute. * @param vin * Unique VIN for a vehicle. * @return a {@link Person} object. * @throws IllegalStateException if failed to convert parameter into {@link IonValue}. */ public static Person findPrimaryOwnerForVehicle(final TransactionExecutor txn, final String vin) { try { log.info("Finding primary owner for vehicle with Vin: {}...", vin); final String query = "SELECT Owners.PrimaryOwner.PersonId FROM VehicleRegistration AS v WHERE v.VIN = ?"; final List<IonValue> parameters = Collections.singletonList(Constants.MAPPER.writeValueAsIonValue(vin)); Result result = txn.execute(query, parameters); final List<IonStruct> documents = ScanTable.toIonStructs(result); ScanTable.printDocuments(documents); if (documents.isEmpty()) { throw new IllegalStateException("Unable to find registrations with VIN: " + vin); } final IonReader reader = IonReaderBuilder.standard().build(documents.get(0)); final String personId = Constants.MAPPER.readValue(reader, LinkedHashMap.class).get("PersonId").toString(); return findPersonFromDocumentId(txn, personId); } catch (IOException ioe) { throw new IllegalStateException(ioe); } } /** * Update the primary owner for a vehicle registration with the given documentId. * * @param txn * The {@link TransactionExecutor} for lambda execute. * @param vin * Unique VIN for a vehicle. * @param documentId * New PersonId for the primary owner. * @throws IllegalStateException if no vehicle registration was found using the given document ID and VIN, or if failed * to convert parameters into {@link IonValue}. */ public static void updateVehicleRegistration(final TransactionExecutor txn, final String vin, final String documentId) { try { log.info("Updating primary owner for vehicle with Vin: {}...", vin); final String query = "UPDATE VehicleRegistration AS v SET v.Owners.PrimaryOwner = ? WHERE v.VIN = ?"; final List<IonValue> parameters = new ArrayList<>(); parameters.add(Constants.MAPPER.writeValueAsIonValue(new Owner(documentId))); parameters.add(Constants.MAPPER.writeValueAsIonValue(vin)); Result result = txn.execute(query, parameters); ScanTable.printDocuments(result); if (result.isEmpty()) { throw new IllegalStateException("Unable to transfer vehicle, could not find registration."); } else { log.info("Successfully transferred vehicle with VIN '{}' to new owner.", vin); } } catch (IOException ioe) { throw new IllegalStateException(ioe); } } public static void main(final String... args) { final String vin = SampleData.VEHICLES.get(0).getVin(); final String primaryOwnerGovId = SampleData.PEOPLE.get(0).getGovId(); final String newPrimaryOwnerGovId = SampleData.PEOPLE.get(1).getGovId(); ConnectToLedger.getDriver().execute(txn -> { final Person primaryOwner = findPrimaryOwnerForVehicle(txn, vin); if (!primaryOwner.getGovId().equals(primaryOwnerGovId)) { // Verify the primary owner. throw new IllegalStateException("Incorrect primary owner identified for vehicle, unable to transfer."); } final String newOwner = Person.getDocumentIdByGovId(txn, newPrimaryOwnerGovId); updateVehicleRegistration(txn, vin, newOwner); }, (retryAttempt) -> log.info("Retrying due to OCC conflict...")); log.info("Successfully transferred vehicle ownership!"); } }
  2. 编译并运行以下程序 (AddSecondaryOwner.java),将次要车主添加到账本VINKM8SRDHF6EU074761中的车辆中。

    2.x
    /* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: MIT-0 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package software.amazon.qldb.tutorial; import java.io.IOException; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.amazon.ion.IonValue; import software.amazon.qldb.Result; import software.amazon.qldb.TransactionExecutor; import software.amazon.qldb.tutorial.model.Owner; import software.amazon.qldb.tutorial.model.Owners; import software.amazon.qldb.tutorial.model.Person; import software.amazon.qldb.tutorial.model.SampleData; /** * Finds and adds secondary owners for a vehicle. * * This code expects that you have AWS credentials setup per: * http://docs.aws.amazon.com/java-sdk/latest/developer-guide/setup-credentials.html */ public final class AddSecondaryOwner { public static final Logger log = LoggerFactory.getLogger(AddSecondaryOwner.class); private AddSecondaryOwner() { } /** * Check whether a secondary owner has already been registered for the given VIN. * * @param txn * The {@link TransactionExecutor} for lambda execute. * @param vin * Unique VIN for a vehicle. * @param secondaryOwnerId * The secondary owner to add. * @return {@code true} if the given secondary owner has already been registered, {@code false} otherwise. * @throws IllegalStateException if failed to convert VIN to an {@link IonValue}. */ public static boolean isSecondaryOwnerForVehicle(final TransactionExecutor txn, final String vin, final String secondaryOwnerId) { try { log.info("Finding secondary owners for vehicle with VIN: {}...", vin); final String query = "SELECT Owners.SecondaryOwners FROM VehicleRegistration AS v WHERE v.VIN = ?"; final List<IonValue> parameters = Collections.singletonList(Constants.MAPPER.writeValueAsIonValue(vin)); final Result result = txn.execute(query, parameters); final Iterator<IonValue> itr = result.iterator(); if (!itr.hasNext()) { return false; } final Owners owners = Constants.MAPPER.readValue(itr.next(), Owners.class); if (null != owners.getSecondaryOwners()) { for (Owner owner : owners.getSecondaryOwners()) { if (secondaryOwnerId.equalsIgnoreCase(owner.getPersonId())) { return true; } } } return false; } catch (IOException ioe) { throw new IllegalStateException(ioe); } } /** * Adds a secondary owner for the specified VIN. * * @param txn * The {@link TransactionExecutor} for lambda execute. * @param vin * Unique VIN for a vehicle. * @param secondaryOwner * The secondary owner to add. * @throws IllegalStateException if failed to convert parameter into an {@link IonValue}. */ public static void addSecondaryOwnerForVin(final TransactionExecutor txn, final String vin, final String secondaryOwner) { try { log.info("Inserting secondary owner for vehicle with VIN: {}...", vin); final String query = String.format("FROM VehicleRegistration AS v WHERE v.VIN = ?" + "INSERT INTO v.Owners.SecondaryOwners VALUE ?"); final IonValue newOwner = Constants.MAPPER.writeValueAsIonValue(new Owner(secondaryOwner)); final IonValue vinAsIonValue = Constants.MAPPER.writeValueAsIonValue(vin); Result result = txn.execute(query, vinAsIonValue, newOwner); log.info("VehicleRegistration Document IDs which had secondary owners added: "); ScanTable.printDocuments(result); } catch (IOException ioe) { throw new IllegalStateException(ioe); } } public static void main(final String... args) { final String vin = SampleData.VEHICLES.get(1).getVin(); final String govId = SampleData.PEOPLE.get(0).getGovId(); ConnectToLedger.getDriver().execute(txn -> { final String documentId = Person.getDocumentIdByGovId(txn, govId); if (isSecondaryOwnerForVehicle(txn, vin, documentId)) { log.info("Person with ID {} has already been added as a secondary owner of this vehicle.", govId); } else { addSecondaryOwnerForVin(txn, vin, documentId); } }); log.info("Secondary owners successfully updated."); } }
    1.x
    /* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: MIT-0 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package software.amazon.qldb.tutorial; import java.io.IOException; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.amazon.ion.IonValue; import software.amazon.qldb.Result; import software.amazon.qldb.TransactionExecutor; import software.amazon.qldb.tutorial.model.Owner; import software.amazon.qldb.tutorial.model.Owners; import software.amazon.qldb.tutorial.model.Person; import software.amazon.qldb.tutorial.model.SampleData; /** * Finds and adds secondary owners for a vehicle. * * This code expects that you have AWS credentials setup per: * http://docs.aws.amazon.com/java-sdk/latest/developer-guide/setup-credentials.html */ public final class AddSecondaryOwner { public static final Logger log = LoggerFactory.getLogger(AddSecondaryOwner.class); private AddSecondaryOwner() { } /** * Check whether a secondary owner has already been registered for the given VIN. * * @param txn * The {@link TransactionExecutor} for lambda execute. * @param vin * Unique VIN for a vehicle. * @param secondaryOwnerId * The secondary owner to add. * @return {@code true} if the given secondary owner has already been registered, {@code false} otherwise. * @throws IllegalStateException if failed to convert VIN to an {@link IonValue}. */ public static boolean isSecondaryOwnerForVehicle(final TransactionExecutor txn, final String vin, final String secondaryOwnerId) { try { log.info("Finding secondary owners for vehicle with VIN: {}...", vin); final String query = "SELECT Owners.SecondaryOwners FROM VehicleRegistration AS v WHERE v.VIN = ?"; final List<IonValue> parameters = Collections.singletonList(Constants.MAPPER.writeValueAsIonValue(vin)); final Result result = txn.execute(query, parameters); final Iterator<IonValue> itr = result.iterator(); if (!itr.hasNext()) { return false; } final Owners owners = Constants.MAPPER.readValue(itr.next(), Owners.class); if (null != owners.getSecondaryOwners()) { for (Owner owner : owners.getSecondaryOwners()) { if (secondaryOwnerId.equalsIgnoreCase(owner.getPersonId())) { return true; } } } return false; } catch (IOException ioe) { throw new IllegalStateException(ioe); } } /** * Adds a secondary owner for the specified VIN. * * @param txn * The {@link TransactionExecutor} for lambda execute. * @param vin * Unique VIN for a vehicle. * @param secondaryOwner * The secondary owner to add. * @throws IllegalStateException if failed to convert parameter into an {@link IonValue}. */ public static void addSecondaryOwnerForVin(final TransactionExecutor txn, final String vin, final String secondaryOwner) { try { log.info("Inserting secondary owner for vehicle with VIN: {}...", vin); final String query = String.format("FROM VehicleRegistration AS v WHERE v.VIN = '%s' " + "INSERT INTO v.Owners.SecondaryOwners VALUE ?", vin); final IonValue newOwner = Constants.MAPPER.writeValueAsIonValue(new Owner(secondaryOwner)); Result result = txn.execute(query, newOwner); log.info("VehicleRegistration Document IDs which had secondary owners added: "); ScanTable.printDocuments(result); } catch (IOException ioe) { throw new IllegalStateException(ioe); } } public static void main(final String... args) { final String vin = SampleData.VEHICLES.get(1).getVin(); final String govId = SampleData.PEOPLE.get(0).getGovId(); ConnectToLedger.getDriver().execute(txn -> { final String documentId = Person.getDocumentIdByGovId(txn, govId); if (isSecondaryOwnerForVehicle(txn, vin, documentId)) { log.info("Person with ID {} has already been added as a secondary owner of this vehicle.", govId); } else { addSecondaryOwnerForVin(txn, vin, documentId); } }, (retryAttempt) -> log.info("Retrying due to OCC conflict...")); log.info("Secondary owners successfully updated."); } }

若要查看 vehicle-registration 分类账中的这些更改,请参阅步骤 6:查看文档修订历史记录