Skip to content

Exception when using attachRow() inside a transaction #2442

Closed

Description

@CordMemescape

Describe the bug
When using attachRow() to create a relationship between two records, the function executes successfully outside of the context of a transaction but fails when executed as part a transaction. The error is not particularly helpful:

Insights listening on port 8081
Server default listening on port 8080
Webserver listening on port 8082
METHOD CALL: internal.addDataLimetrack duration: 19199ms numQueries: 0 authenticatedUser: 3
DatabaseException: Failed to update row, no rows updated
#0      DatabaseConnection.updateRow (package:serverpod/src/database/adapters/postgres/database_connection.dart:226:7)
<asynchronous suspension>
#1      AddressAttachRowRepository.country (package:limetrack_server/src/generated/address.dart:508:5)
<asynchronous suspension>
#2      InternalEndpoint.addDataLimetrack.<anonymous closure> (package:limetrack_server/src/endpoints/internal_endpoint.dart:802:7)
<asynchronous suspension>
#3      PgConnectionImplementation.runTx.<anonymous closure> (package:postgres/src/v3/connection.dart:480:24)
<asynchronous suspension>
#4      Pool.withResource (package:pool/pool.dart:127:14)
<asynchronous suspension>
#5      PoolImplementation.withConnection (package:postgres/src/pool/pool_impl.dart:153:16)
<asynchronous suspension>
#6      Database.transaction (package:serverpod/src/database/database.dart:291:12)
<asynchronous suspension>
#7      InternalEndpoint.addDataLimetrack (package:limetrack_server/src/endpoints/internal_endpoint.dart:800:5)
<asynchronous suspension>
#8      EndpointDispatch.handleUriCall (package:serverpod/src/server/endpoint_dispatch.dart:127:20)
<asynchronous suspension>
#9      Server._handleRequest (package:serverpod/src/server/server.dart:296:18)
<asynchronous suspension>

To Reproduce
Steps to reproduce the behavior:

  1. Create a project with a simple one-to-many relationship
  2. Insert the rows required to create the records
  3. Use attachRow() to create the relationship between the records
  4. Repeat steps 2 and 3 inside a transaction
  5. See error

Expected behavior
I expected to be able to create the necessary relationships - using attachRow - within the context of a transaction. It's important to be able to use a transaction in order to rollback a series of inserts if anything goes wrong.

Serverpod versions

  • CLI Version: Serverpod version: 2.0.1
  • Library version:
    serverpod: 2.0.1
    serverpod_auth_server: 2.0.1
    serverpod_serialization: 2.0.1

Platform information
Server running in development mode on an Apple MacBook M1. Standard Docker deployment.

Code snippet

    // Lookups
    CompanyType? companyType = await CompanyType.db.findFirstRow(
      session,
      where: (t) => t.name.ilike('%private company%'),
    );

    Country? country = await Country.db.findFirstRow(
      session,
      where: (t) => t.name.ilike('%united kingdom%'),
    );

    // Data
    Address address = Address(line1: 'Address line 1', town: 'Town', postcode: 'PostCode');
    Carrier carrier = Carrier(companyName: 'Company Name');

    // Add data without transaction - WORKS
    Address newAddress = await Address.db.insertRow(session, address);
    await Address.db.attachRow.country(session, newAddress, country!);

    Carrier newCarrier = await Carrier.db.insertRow(session, carrier);
    await Carrier.db.attachRow.companyType(session, newCarrier, companyType!);
    await Carrier.db.attachRow.registeredAddress(session, newCarrier, newAddress);

    // Add data with transaction - FAILS
    await session.db.transaction((transaction) async {
      Address newTxnAddress = await Address.db.insertRow(session, address, transaction: transaction);
      // This call fails with the above exception
      await Address.db.attachRow.country(session, newTxnAddress, country!);

      Carrier newTxnCarrier = await Carrier.db.insertRow(session, carrier, transaction: transaction);
      await Carrier.db.attachRow.companyType(session, newTxnCarrier, companyType!);
      await Carrier.db.attachRow.registeredAddress(session, newCarrier, newTxnAddress);
    });

Activity

  1. CordMemescape commented on Jul 6, 2024

    @CordMemescape
    Author

    I've retested the above, replacing the attachRow() calls with updateRow(), with the same results. The updateRow() call fails inside the transaction with the following error. The failure is unsurprising because attachRow() simply calls update under the hood.

    DatabaseException: Failed to update row, no rows updated
    #0      DatabaseConnection.updateRow (package:serverpod/src/database/adapters/postgres/database_connection.dart:226:7)
    <asynchronous suspension>
    #1      InternalEndpoint.addDataLimetrackUsingUpdateRow.<anonymous closure> (package:limetrack_server/src/endpoints/internal_endpoint.dart:840:7)
    <asynchronous suspension>
    #2      PgConnectionImplementation.runTx.<anonymous closure> (package:postgres/src/v3/connection.dart:480:24)
    <asynchronous suspension>
    #3      Pool.withResource (package:pool/pool.dart:127:14)
    <asynchronous suspension>
    #4      PoolImplementation.withConnection (package:postgres/src/pool/pool_impl.dart:153:16)
    <asynchronous suspension>
    #5      Database.transaction (package:serverpod/src/database/database.dart:291:12)
    <asynchronous suspension>
    #6      InternalEndpoint.addDataLimetrackUsingUpdateRow (package:limetrack_server/src/endpoints/internal_endpoint.dart:837:5)
    <asynchronous suspension>
    #7      EndpointDispatch.handleUriCall (package:serverpod/src/server/endpoint_dispatch.dart:127:20)
    <asynchronous suspension>
    #8      Server._handleRequest (package:serverpod/src/server/server.dart:296:18)
    <asynchronous suspension>
    
    
  2. SandPod commented on Jul 8, 2024

    @SandPod
    Contributor

    Hey @CordMemescape! 👋

    Just a simple sanity check question: do you get this error even if you remove the queries performed outside the transaction? (I just want to validate that there are no index restrictions on the table that prevent multiple addresses from being connected to the same country).

    Could you provide the minimum models required to reproduce this issue? That would help us when debugging.

  3. CordMemescape commented on Jul 8, 2024

    @CordMemescape
    Author

    Hey @SandPod! Yes, the error happens whether those queries are inside or outside of the transaction. In my original code, they were all done inside the transaction and I only moved them out for brevity and so that I could include the code that worked along with the code that didn't.

    Initially I thought that the issue might be because of nested transactions, particularly where I was dealing with lists. I have several functions that accept lists as parameters and attempt to perform the inserts in the context of transactions so that if anything fails, I can roll the whole lot back. I stripped everything out to the most basic example that I could, just to confirm that the issue still happens. And it does.

    Since posting this, I went back to take a closer look the attach() and attachRow() functions. They call update<T>() under the hood but do not use a transaction parameter. Therefore, since the inserts are done within the context of the transaction, the attaches will not be able to 'see' the changes until they are committed. In other words, the foreign keys referenced by attach()/attachRow() do not exist at the time the functions are called. This will cause an exception which is what I suspect we are seeing. One solution might be to commit the changes before calling attach()/attachRow() but this may not be desirable, especially if the attach is merely part of a larger transaction that you really only want to commit right at the very end - when everything has been done successfully.

    Here are the four main models used in the above.

    ### Address 
    class: Address
    table: addresses
    
    fields:
      line1: String
      line2: String?
      line3: String?
      town: String?
      postcode: String
      country: Country?, relation(optional)
      deleted: bool?
    
    indexes:
      address_idx:
        fields: line1, postcode
    
    
    ### Country 
    class: Country
    table: countries
    
    fields:
      name: String
      alpha2Code: String
      alpha3Code: String
      numericCode: int
      language: String?
      currency: String?
      supported: bool?
    
    indexes:
      country_unique_idx:
        fields: numericCode
        unique: true
      country_name_idx:
        fields: name
      country_alpha2Code_idx:
        fields: alpha2Code
      country_alpha3Code_idx:
        fields: alpha3Code
      country_language_idx:
        fields: language
    
    
    ### Carrier
    class: Carrier
    table: carriers
    
    fields:
      companyName: String
      companyNumber: String?
      registeredAddress: Address?, relation(optional)
      companyType: CompanyType?, relation(optional)
      tradingAs: String?
      natureOfBusiness: String?
      wasteCarrierRegistrations: List<WasteCarrierRegistration>?, relation(optional)
      environmentPermits: List<EnvironmentPermit>?, relation(optional)
      wasteExemptions: List<WasteExemption>?, relation(optional)
      weightLimit: int?
      carrierUsers: List<CarrierUser>?, relation(name=carrier_carrierUser, optional)
      carrierSites: List<CarrierSite>?, relation(name=carrier_carrierSite, optional)
      carrierVehicles: List<CarrierVehicle>?, relation(name=carrier_carrierVehicle, optional)
      transferJunctions: List<TransferJunction>?, relation(name=carrier_transfer, optional)
      deleted: bool?
    
    indexes:
      carrier_unique_idx:
        fields: companyName, companyNumber
        unique: true
      carrier_company_name_idx:
        fields: companyName
      carrier_company_number_idx:
        fields: companyNumber
      carrier_registered_address_idx:
        fields: registeredAddressId
      carrier_trading_as_idx:
        fields: tradingAs
    
    
    ### CompanyType 
    class: CompanyType
    table: company_types
    
    fields:
      name: String
      categoryType: CategoryType?, relation(optional)
      description: String?
      deleted: bool?
    
    indexes:
      company_type_unique_idx:
        fields: name
        unique: true
    
  4. SandPod commented on Jul 8, 2024

    @SandPod
    Contributor

    @CordMemescape Thank you for the additional information.

    I think your findings are correct and we are missing the transaction parameter for the generate attach methods. Here is a snippet of a generated class in the test project where the optional transaction parameter is missing:

    Future<void> citizens(
    _i1.Session session,
    CityWithLongTableName cityWithLongTableName,
    _i2.PersonWithLongTableName personWithLongTableName,
    ) async {
    if (personWithLongTableName.id == null) {
    throw ArgumentError.notNull('personWithLongTableName.id');
    }
    if (cityWithLongTableName.id == null) {
    throw ArgumentError.notNull('cityWithLongTableName.id');
    }
    var $personWithLongTableName = _i2.PersonWithLongTableNameImplicit(
    personWithLongTableName,
    $_cityWithLongTableNameThatIsStillValidCitizensCityWithLon4fe0Id:
    cityWithLongTableName.id,
    );
    await session.db.updateRow<_i2.PersonWithLongTableName>(
    $personWithLongTableName,
    columns: [
    _i2.PersonWithLongTableName.t
    .$_cityWithLongTableNameThatIsStillValidCitizensCityWithLon4fe0Id
    ],
    );
    }

    Luckily this is something we can fix as a non breaking change.

  5. added
    bug
    on Jul 8, 2024
  6. self-assigned this
    on Aug 22, 2024
  7. moved this from Now 🔥 to Done 🚀 in Serverpod Frameworkson Aug 26, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bug

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions