From 8c7e13554e3ceb5def5ef0e4e7a602aa473e96a5 Mon Sep 17 00:00:00 2001 From: James Reategui Date: Thu, 20 Jul 2023 14:18:24 -0400 Subject: [PATCH] PRO-1653 add manuf token id col, change pkey, update fkeys (#163) * add manuf token id col, change pkey, update fkeys * fixed compilation, couple test failures * minor name change * fix test --- cmd/devices-api/remake_aftermarket_topic.go | 2 +- internal/controllers/nft_controller.go | 4 +- .../controllers/user_devices_controller.go | 2 +- .../user_devices_controller_test.go | 8 +- .../user_integrations_controller.go | 34 ++- .../user_integrations_controller_test.go | 29 +- internal/middleware/owner/owner.go | 2 +- internal/services/autopi/integration.go | 4 +- internal/services/autopi_api_service_test.go | 2 +- .../services/contracts_events_consumer.go | 2 +- internal/services/fingerprint/consumer.go | 3 +- .../services/fingerprint/consumer_test.go | 4 +- internal/test/helpers.go | 9 +- ...50333_aftermarket_pkey_change_add_make.sql | 49 ++++ models/aftermarket_devices.go | 102 ++++--- models/dcn.go | 9 - models/external_vin_data.go | 228 +-------------- models/meta_transaction_requests.go | 6 +- models/psql_upsert.go | 3 - models/user_devices.go | 265 ------------------ models/vehicle_nfts.go | 2 +- 21 files changed, 165 insertions(+), 604 deletions(-) create mode 100644 migrations/20230719150333_aftermarket_pkey_change_add_make.sql diff --git a/cmd/devices-api/remake_aftermarket_topic.go b/cmd/devices-api/remake_aftermarket_topic.go index 2d52f7f99..338533ff1 100644 --- a/cmd/devices-api/remake_aftermarket_topic.go +++ b/cmd/devices-api/remake_aftermarket_topic.go @@ -73,7 +73,7 @@ func remakeAftermarketTopic(ctx context.Context, pdb db.Store, producer sarama.S if err := reg.Register2(&services.AftermarketDeviceVehicleMapping{ AftermarketDevice: services.AftermarketDeviceVehicleMappingAftermarketDevice{ - Address: common.BytesToAddress(amd.EthereumAddress.Bytes), + Address: common.BytesToAddress(amd.EthereumAddress), Token: amd.TokenID.Int(nil), Serial: amd.Serial, IntegrationID: integ.Id, diff --git a/internal/controllers/nft_controller.go b/internal/controllers/nft_controller.go index 6eefb2fc9..f5b0eea16 100644 --- a/internal/controllers/nft_controller.go +++ b/internal/controllers/nft_controller.go @@ -386,7 +386,7 @@ func (nc *NFTController) GetAftermarketDeviceNFTMetadata(c *fiber.Ctx) error { return err } var name string - if three, err := mnemonic.EntropyToMnemonicThreeWords(unit.EthereumAddress.Bytes); err == nil { + if three, err := mnemonic.EntropyToMnemonicThreeWords(unit.EthereumAddress); err == nil { name = strings.Join(three, " ") } @@ -395,7 +395,7 @@ func (nc *NFTController) GetAftermarketDeviceNFTMetadata(c *fiber.Ctx) error { Description: name + ", a DIMO hardware device.", Image: fmt.Sprintf("%s/v1/aftermarket/device/%s/image", nc.Settings.DeploymentBaseURL, tid), Attributes: []NFTAttribute{ - {TraitType: "Ethereum Address", Value: common.BytesToAddress(unit.EthereumAddress.Bytes).String()}, + {TraitType: "Ethereum Address", Value: common.BytesToAddress(unit.EthereumAddress).String()}, {TraitType: "Serial Number", Value: unit.Serial}, }, }) diff --git a/internal/controllers/user_devices_controller.go b/internal/controllers/user_devices_controller.go index b959be0b5..e46f51f39 100644 --- a/internal/controllers/user_devices_controller.go +++ b/internal/controllers/user_devices_controller.go @@ -923,7 +923,7 @@ func (udc *UserDevicesController) UpdateVIN(c *fiber.Ctx) error { } found, err := models.AftermarketDevices( - models.AftermarketDeviceWhere.EthereumAddress.EQ(null.BytesFrom(recAddr.Bytes())), + models.AftermarketDeviceWhere.EthereumAddress.EQ(recAddr.Bytes()), ).Exists(c.Context(), udc.DBS().Reader) if err != nil { return err diff --git a/internal/controllers/user_devices_controller_test.go b/internal/controllers/user_devices_controller_test.go index 3de5806a9..5c3bec864 100644 --- a/internal/controllers/user_devices_controller_test.go +++ b/internal/controllers/user_devices_controller_test.go @@ -463,7 +463,7 @@ func (s *UserDevicesControllerTestSuite) TestGetMyUserDevices() { integration := test.BuildIntegrationGRPC(constants.AutoPiVendor, 10, 0) dd := test.BuildDeviceDefinitionGRPC(ksuid.New().String(), "Ford", "F150", 2020, integration) ud := test.SetupCreateUserDevice(s.T(), s.testUserID, dd[0].DeviceDefinitionId, nil, "", s.pdb) - _ = test.SetupCreateAftermarketDevice(s.T(), testUserID, unitID, func(s string) *string { return &s }(deviceID), s.pdb) + _ = test.SetupCreateAftermarketDevice(s.T(), testUserID, nil, unitID, func(s string) *string { return &s }(deviceID), s.pdb) _ = test.SetupCreateUserDeviceAPIIntegration(s.T(), unitID, deviceID, ud.ID, integration.Id, s.pdb) addr := "67B94473D81D0cd00849D563C94d0432Ac988B49" @@ -507,7 +507,7 @@ func (s *UserDevicesControllerTestSuite) TestGetMyUserDevicesNoDuplicates() { integration := test.BuildIntegrationGRPC(constants.AutoPiVendor, 10, 0) dd := test.BuildDeviceDefinitionGRPC(ksuid.New().String(), "Ford", "F150", 2020, integration) ud := test.SetupCreateUserDeviceWithDeviceID(s.T(), userID, deviceID, dd[0].DeviceDefinitionId, nil, "", s.pdb) - _ = test.SetupCreateAftermarketDevice(s.T(), userID, unitID, func(s string) *string { return &s }(deviceID), s.pdb) + _ = test.SetupCreateAftermarketDevice(s.T(), userID, nil, unitID, func(s string) *string { return &s }(deviceID), s.pdb) _ = test.SetupCreateUserDeviceAPIIntegration(s.T(), unitID, deviceID, ud.ID, integration.Id, s.pdb) addr := "67B94473D81D0cd00849D563C94d0432Ac988B49" @@ -650,7 +650,7 @@ func (s *UserDevicesControllerTestSuite) TestNameValidate() { func (s *UserDevicesControllerTestSuite) TestPatchName() { ud := test.SetupCreateUserDevice(s.T(), s.testUserID, ksuid.New().String(), nil, "", s.pdb) deviceID := uuid.New().String() - apunit := test.SetupCreateAftermarketDevice(s.T(), s.testUserID, uuid.NewString(), &deviceID, s.pdb) + apunit := test.SetupCreateAftermarketDevice(s.T(), s.testUserID, nil, uuid.NewString(), &deviceID, s.pdb) autoPiIntID := ksuid.New().String() vehicleID := 3214 _ = test.SetupCreateUserDeviceAPIIntegration(s.T(), apunit.Serial, deviceID, ud.ID, autoPiIntID, s.pdb) @@ -804,7 +804,7 @@ func (s *UserDevicesControllerTestSuite) TestGetRange() { ddID := ksuid.New().String() integration := test.BuildIntegrationGRPC(constants.AutoPiVendor, 10, 0) smartCarIntegration := test.BuildIntegrationGRPC(constants.SmartCarVendor, 10, 0) - _ = test.SetupCreateAftermarketDevice(s.T(), testUserID, autoPiUnitID, &autoPiDeviceID, s.pdb) + _ = test.SetupCreateAftermarketDevice(s.T(), testUserID, nil, autoPiUnitID, &autoPiDeviceID, s.pdb) gddir := []*grpc.GetDeviceDefinitionItemResponse{ { diff --git a/internal/controllers/user_integrations_controller.go b/internal/controllers/user_integrations_controller.go index 4e67fd4f2..9a90d24e1 100644 --- a/internal/controllers/user_integrations_controller.go +++ b/internal/controllers/user_integrations_controller.go @@ -483,10 +483,8 @@ func (udc *UserDevicesController) GetAutoPiUnitInfo(c *fiber.Ctx) error { tokenID = dbUnit.TokenID.Int(nil) } - if dbUnit.EthereumAddress.Valid { - addr := common.BytesToAddress(dbUnit.EthereumAddress.Bytes) - ethereumAddress = &addr - } + addr := common.BytesToAddress(dbUnit.EthereumAddress) + ethereumAddress = &addr if dbUnit.OwnerAddress.Valid { addr := common.BytesToAddress(dbUnit.OwnerAddress.Bytes) @@ -719,7 +717,7 @@ func (udc *UserDevicesController) GetAutoPiPairMessage(c *fiber.Ctx) error { return opaqueInternalError } - var autoPiUnit *models.AftermarketDevice + var aftermarketDevice *models.AftermarketDevice if extID := c.Query("external_id"); extID != "" { unitID, err := uuid.Parse(extID) @@ -727,7 +725,7 @@ func (udc *UserDevicesController) GetAutoPiPairMessage(c *fiber.Ctx) error { return err } - autoPiUnit, err = models.AftermarketDevices( + aftermarketDevice, err = models.AftermarketDevices( models.AftermarketDeviceWhere.Serial.EQ(unitID.String()), qm.Load(models.AftermarketDeviceRels.PairRequest), qm.Load(models.AftermarketDeviceRels.UnpairRequest), @@ -753,21 +751,21 @@ func (udc *UserDevicesController) GetAutoPiPairMessage(c *fiber.Ctx) error { } // Conflict with web2 pairing? - if autoPiUnit != nil && (!udai.Serial.Valid || udai.Serial.String != autoPiUnit.Serial) { + if aftermarketDevice != nil && (!udai.Serial.Valid || udai.Serial.String != aftermarketDevice.Serial) { return fiber.NewError(fiber.StatusConflict, "Vehicle already paired with another AutoPi.") } - autoPiUnit = udai.R.SerialAftermarketDevice + aftermarketDevice = udai.R.SerialAftermarketDevice } - if autoPiUnit.R.PairRequest != nil && autoPiUnit.R.PairRequest.Status != "Failed" { - if autoPiUnit.R.PairRequest.Status == models.MetaTransactionRequestStatusConfirmed { + if aftermarketDevice.R.PairRequest != nil && aftermarketDevice.R.PairRequest.Status != "Failed" { + if aftermarketDevice.R.PairRequest.Status == models.MetaTransactionRequestStatusConfirmed { return fiber.NewError(fiber.StatusConflict, "AutoPi already paired.") } return fiber.NewError(fiber.StatusConflict, "AutoPi pairing in process.") } - if autoPiUnit.TokenID.IsZero() { + if aftermarketDevice.TokenID.IsZero() { return fiber.NewError(fiber.StatusConflict, "AutoPi not yet minted.") } @@ -775,11 +773,11 @@ func (udc *UserDevicesController) GetAutoPiPairMessage(c *fiber.Ctx) error { return fiber.NewError(fiber.StatusConflict, "Vehicle not yet minted.") } - if !autoPiUnit.OwnerAddress.Valid { + if !aftermarketDevice.OwnerAddress.Valid { return fiber.NewError(fiber.StatusConflict, "Device not yet claimed.") } - apToken := autoPiUnit.TokenID.Int(nil) + apToken := aftermarketDevice.TokenID.Int(nil) vehicleToken := ud.R.VehicleNFT.TokenID.Int(nil) user, err := udc.usersClient.GetUser(c.Context(), &pb.GetUserRequest{Id: userID}) @@ -793,7 +791,7 @@ func (udc *UserDevicesController) GetAutoPiPairMessage(c *fiber.Ctx) error { } if udc.Settings.IsProduction() { - if common.HexToAddress(*user.EthereumAddress) != common.BytesToAddress(autoPiUnit.OwnerAddress.Bytes) { + if common.HexToAddress(*user.EthereumAddress) != common.BytesToAddress(aftermarketDevice.OwnerAddress.Bytes) { return fiber.NewError(fiber.StatusConflict, "AutoPi claimed by another user.") } } @@ -988,7 +986,7 @@ func (udc *UserDevicesController) PostPairAutoPi(c *fiber.Ctx) error { if recAddr, err := helpers.Ecrecover(hash.Bytes(), aftermarketDeviceSig); err != nil { return err - } else if recAddr != common.BytesToAddress(autoPiUnit.EthereumAddress.Bytes) { + } else if recAddr != common.BytesToAddress(autoPiUnit.EthereumAddress) { return fiber.NewError(fiber.StatusBadRequest, "Incorrect aftermarket device signature.") } @@ -1351,7 +1349,7 @@ func (udc *UserDevicesController) PostUnclaimAutoPi(c *fiber.Ctx) error { logger.Info().Msg("Got unclaim request.") - unit, err := models.FindAftermarketDevice(c.Context(), udc.DBS().Reader, unitID) + unit, err := models.AftermarketDevices(models.AftermarketDeviceWhere.Serial.EQ(unitID)).One(c.Context(), udc.DBS().Reader) if err != nil { if err == sql.ErrNoRows { return fiber.NewError(fiber.StatusNotFound, "AutoPi not minted, or unit ID invalid.") @@ -1422,7 +1420,7 @@ func (udc *UserDevicesController) PostClaimAutoPi(c *fiber.Ctx) error { return fiber.NewError(fiber.StatusInternalServerError, "Internal error.") } - if unit.TokenID.IsZero() || !unit.EthereumAddress.Valid { + if unit.TokenID.IsZero() { return fiber.NewError(fiber.StatusNotFound, "AutoPi not minted.") } @@ -1497,7 +1495,7 @@ func (udc *UserDevicesController) PostClaimAutoPi(c *fiber.Ctx) error { return err } - realAmAddr := common.BytesToAddress(unit.EthereumAddress.Bytes) + realAmAddr := common.BytesToAddress(unit.EthereumAddress) if recAmAddr != realAmAddr { return fiber.NewError(fiber.StatusBadRequest, "Aftermarket device signature invalid.") diff --git a/internal/controllers/user_integrations_controller_test.go b/internal/controllers/user_integrations_controller_test.go index 1c5283e55..ed52bcacd 100644 --- a/internal/controllers/user_integrations_controller_test.go +++ b/internal/controllers/user_integrations_controller_test.go @@ -528,7 +528,7 @@ func (s *UserIntegrationsControllerTestSuite) TestPostAutoPiBlockedForDuplicateD deviceID = "1dd96159-3bb2-9472-91f6-72fe9211cfeb" unitID = "431d2e89-46f1-6884-6226-5d1ad20c84d9" ) - _ = test.SetupCreateAftermarketDevice(s.T(), testUserID, unitID, func(s string) *string { return &s }(deviceID), s.pdb) + _ = test.SetupCreateAftermarketDevice(s.T(), testUserID, nil, unitID, func(s string) *string { return &s }(deviceID), s.pdb) test.SetupCreateUserDeviceAPIIntegration(s.T(), unitID, deviceID, ud.ID, integration.Id, s.pdb) req := fmt.Sprintf(`{ @@ -564,7 +564,7 @@ func (s *UserIntegrationsControllerTestSuite) TestPostAutoPiBlockedForDuplicateD deviceID = "1dd96159-3bb2-9472-91f6-72fe9211cfeb" unitID = "431d2e89-46f1-6884-6226-5d1ad20c84d9" ) - _ = test.SetupCreateAftermarketDevice(s.T(), testUserID, unitID, func(s string) *string { return &s }(deviceID), s.pdb) + _ = test.SetupCreateAftermarketDevice(s.T(), testUserID, nil, unitID, func(s string) *string { return &s }(deviceID), s.pdb) // test user ud2 := test.SetupCreateUserDevice(s.T(), testUser2, dd[0].DeviceDefinitionId, nil, "", s.pdb) @@ -594,7 +594,7 @@ func (s *UserIntegrationsControllerTestSuite) TestGetAutoPiInfoNoUDAI_ShouldUpda app.Get("/autopi/unit/:unitID", test.AuthInjectorTestHandler(testUserID), owner.AutoPi(s.pdb, s.userClient, &logger), c.GetAutoPiUnitInfo) // arrange const unitID = "431d2e89-46f1-6884-6226-5d1ad20c84d9" - test.SetupCreateAftermarketDevice(s.T(), "", unitID, nil, s.pdb) + test.SetupCreateAftermarketDevice(s.T(), "", nil, unitID, nil, s.pdb) autopiAPISvc.EXPECT().GetDeviceByUnitID(unitID).Times(1).Return(&services.AutoPiDongleDevice{ IsUpdated: false, UnitID: unitID, @@ -632,7 +632,7 @@ func (s *UserIntegrationsControllerTestSuite) TestGetAutoPiInfoNoUDAI_UpToDate() app.Get("/autopi/unit/:unitID", test.AuthInjectorTestHandler(testUserID), owner.AutoPi(s.pdb, s.userClient, &logger), c.GetAutoPiUnitInfo) // arrange const unitID = "431d2e89-46f1-6884-6226-5d1ad20c84d9" - test.SetupCreateAftermarketDevice(s.T(), "", unitID, nil, s.pdb) + test.SetupCreateAftermarketDevice(s.T(), "", nil, unitID, nil, s.pdb) autopiAPISvc.EXPECT().GetDeviceByUnitID(unitID).Times(1).Return(&services.AutoPiDongleDevice{ IsUpdated: true, UnitID: unitID, @@ -667,7 +667,7 @@ func (s *UserIntegrationsControllerTestSuite) TestGetAutoPiInfoNoUDAI_FutureUpda app.Get("/autopi/unit/:unitID", test.AuthInjectorTestHandler(testUserID), owner.AutoPi(s.pdb, s.userClient, &logger), c.GetAutoPiUnitInfo) // arrange const unitID = "431d2e89-46f1-6884-6226-5d1ad20c84d9" - test.SetupCreateAftermarketDevice(s.T(), "", unitID, nil, s.pdb) + test.SetupCreateAftermarketDevice(s.T(), "", nil, unitID, nil, s.pdb) autopiAPISvc.EXPECT().GetDeviceByUnitID(unitID).Times(1).Return(&services.AutoPiDongleDevice{ IsUpdated: false, UnitID: unitID, @@ -703,7 +703,7 @@ func (s *UserIntegrationsControllerTestSuite) TestGetAutoPiInfoNoUDAI_ShouldUpda app.Get("/autopi/unit/:unitID", test.AuthInjectorTestHandler(testUserID), owner.AutoPi(s.pdb, s.userClient, &logger), c.GetAutoPiUnitInfo) // arrange const unitID = "431d2e89-46f1-6884-6226-5d1ad20c84d9" - test.SetupCreateAftermarketDevice(s.T(), "", unitID, nil, s.pdb) + test.SetupCreateAftermarketDevice(s.T(), "", nil, unitID, nil, s.pdb) autopiAPISvc.EXPECT().GetDeviceByUnitID(unitID).Times(1).Return(&services.AutoPiDongleDevice{ IsUpdated: false, UnitID: unitID, @@ -770,22 +770,23 @@ func (s *UserIntegrationsControllerTestSuite) TestPairAftermarketNoLegacy() { } s.Require().NoError(vnft.Insert(s.ctx, s.pdb.DBS().Writer, boil.Infer())) - apUnit := test.SetupCreateAftermarketDevice(s.T(), testUserID, unitID, &deviceID, s.pdb) - apUnit.TokenID = types.NewNullDecimal(decimal.New(5, 0)) - apUnit.EthereumAddress = null.BytesFrom(common.BigToAddress(big.NewInt(2)).Bytes()) - apUnit.OwnerAddress = null.BytesFrom(userAddr.Bytes()) - _, err = apUnit.Update(s.ctx, s.pdb.DBS().Writer, boil.Infer()) - s.Require().NoError(err) + aftermarketDevice := test.SetupCreateAftermarketDevice(s.T(), testUserID, common.BigToAddress(big.NewInt(2)).Bytes(), unitID, &deviceID, s.pdb) + aftermarketDevice.TokenID = types.NewNullDecimal(decimal.New(5, 0)) + aftermarketDevice.OwnerAddress = null.BytesFrom(userAddr.Bytes()) + row, errAMD := aftermarketDevice.Update(s.ctx, s.pdb.DBS().Writer, boil.Infer()) + s.Assert().Equal(int64(1), row) + s.Require().NoError(errAMD) app := fiber.New() app.Use(test.AuthInjectorTestHandler(userID)) app.Get("/:userDeviceID/pair", c.GetAutoPiPairMessage) app.Post("/:userDeviceID/pair", c.PostPairAutoPi) - req := test.BuildRequest("GET", "/"+ud.ID+"/pair?external_id="+unitID, "") + req := test.BuildRequest("GET", "/"+ud.ID+"/pair?external_id="+aftermarketDevice.Serial, "") res, err := app.Test(req) s.Require().NoError(err) + s.Require().Equal(fiber.StatusOK, res.StatusCode) // todo issue - this is returning 409 instead of 200? due to change in how get unit? defer res.Body.Close() var td signer.TypedData @@ -799,7 +800,7 @@ func (s *UserIntegrationsControllerTestSuite) TestPairAftermarketNoLegacy() { userSig[64] += 27 in := map[string]any{ - "externalId": apUnit.Serial, + "externalId": aftermarketDevice.Serial, "signature": hexutil.Bytes(userSig).String(), } diff --git a/internal/middleware/owner/owner.go b/internal/middleware/owner/owner.go index 0a4dea2d9..a812d72c2 100644 --- a/internal/middleware/owner/owner.go +++ b/internal/middleware/owner/owner.go @@ -95,7 +95,7 @@ func AutoPi(dbs db.Store, usersClient pb.UserServiceClient, logger *zerolog.Logg c.Locals("unitID", unitID) c.Locals("logger", &logger) - autopiUnit, err := models.FindAftermarketDevice(c.Context(), dbs.DBS().Reader, unitID) + autopiUnit, err := models.AftermarketDevices(models.AftermarketDeviceWhere.Serial.EQ(unitID)).One(c.Context(), dbs.DBS().Reader) if err != nil { if errors.Is(err, sql.ErrNoRows) { return fiber.NewError(fiber.StatusNotFound, "AutoPi not minted, or unit ID invalid.") diff --git a/internal/services/autopi/integration.go b/internal/services/autopi/integration.go index 9181db1c9..f1562f484 100644 --- a/internal/services/autopi/integration.go +++ b/internal/services/autopi/integration.go @@ -256,7 +256,7 @@ func (i *Integration) Pair(ctx context.Context, autoPiTokenID, vehicleTokenID *b err = i.apReg.Register2(&services.AftermarketDeviceVehicleMapping{ AftermarketDevice: services.AftermarketDeviceVehicleMappingAftermarketDevice{ - Address: common.BytesToAddress(autoPiModel.EthereumAddress.Bytes), + Address: common.BytesToAddress(autoPiModel.EthereumAddress), Token: autoPiTokenID, Serial: autoPiModel.Serial, IntegrationID: integ.Id, @@ -367,7 +367,7 @@ func (i *Integration) Unpair(ctx context.Context, autoPiTokenID, vehicleTokenID return err } - err = i.apReg.Deregister2(common.BytesToAddress(autoPiModel.EthereumAddress.Bytes)) + err = i.apReg.Deregister2(common.BytesToAddress(autoPiModel.EthereumAddress)) if err != nil { return err } diff --git a/internal/services/autopi_api_service_test.go b/internal/services/autopi_api_service_test.go index edd80141e..814b7d14b 100644 --- a/internal/services/autopi_api_service_test.go +++ b/internal/services/autopi_api_service_test.go @@ -95,7 +95,7 @@ func (s *AutoPiAPIServiceTestSuite) TestCommandRaw() { apiURL = "https://mock.town" jobID = "321" ) - _ = test.SetupCreateAftermarketDevice(s.T(), testUserID, unitID, func(s string) *string { return &s }(deviceID), s.pdb) + _ = test.SetupCreateAftermarketDevice(s.T(), testUserID, nil, unitID, func(s string) *string { return &s }(deviceID), s.pdb) // http client mock httpmock.Activate() defer httpmock.DeactivateAndReset() diff --git a/internal/services/contracts_events_consumer.go b/internal/services/contracts_events_consumer.go index c174f1297..8e88fc5fc 100644 --- a/internal/services/contracts_events_consumer.go +++ b/internal/services/contracts_events_consumer.go @@ -321,7 +321,7 @@ func (c *ContractsEventsConsumer) setMintedAfterMarketDevice(e *ContractEventDat amd := models.AftermarketDevice{ Serial: device.UnitID, - EthereumAddress: null.BytesFrom(args.AftermarketDeviceAddress.Bytes()), + EthereumAddress: args.AftermarketDeviceAddress.Bytes(), TokenID: types.NewNullDecimal(new(decimal.Big).SetBigMantScale(args.TokenId, 0)), } _ = amd.Metadata.Marshal(amdMd) diff --git a/internal/services/fingerprint/consumer.go b/internal/services/fingerprint/consumer.go index bd6b89d71..11aaafda1 100644 --- a/internal/services/fingerprint/consumer.go +++ b/internal/services/fingerprint/consumer.go @@ -18,7 +18,6 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/crypto" "github.com/rs/zerolog" - "github.com/volatiletech/null/v8" "github.com/volatiletech/sqlboiler/v4/queries/qm" ) @@ -107,7 +106,7 @@ func (c *Consumer) Handle(ctx context.Context, event *Event) error { } ad, err := models.AftermarketDevices( - models.AftermarketDeviceWhere.EthereumAddress.EQ(null.BytesFrom(addr.Bytes())), + models.AftermarketDeviceWhere.EthereumAddress.EQ(addr.Bytes()), qm.Load(qm.Rels(models.AftermarketDeviceRels.VehicleToken, models.VehicleNFTRels.Claim)), ).One(ctx, c.DBS.DBS().Reader) if err != nil { diff --git a/internal/services/fingerprint/consumer_test.go b/internal/services/fingerprint/consumer_test.go index 44f7b656b..c40d7b5f7 100644 --- a/internal/services/fingerprint/consumer_test.go +++ b/internal/services/fingerprint/consumer_test.go @@ -110,7 +110,7 @@ func (s *ConsumerTestSuite) TestVinCredentialerHandler() { TokenID: types.NewNullDecimal(new(decimal.Big).SetBigMantScale(big.NewInt(13), 0)), VehicleTokenID: types.NewNullDecimal(new(decimal.Big).SetBigMantScale(tokenID, 0)), Beneficiary: null.BytesFrom(common.BytesToAddress([]byte{uint8(1)}).Bytes()), - EthereumAddress: ownerAddress, + EthereumAddress: ownerAddress.Bytes, } userDevice := models.UserDevice{ @@ -203,7 +203,7 @@ func (s *ConsumerTestSuite) TestVinCredentialerHandler() { UpdatedAt: time.Now(), TokenID: types.NewNullDecimal(new(decimal.Big).SetBigMantScale(big.NewInt(13), 0)), Beneficiary: null.BytesFrom(common.BytesToAddress([]byte{uint8(1)}).Bytes()), - EthereumAddress: ownerAddress, + EthereumAddress: ownerAddress.Bytes, }, }, } diff --git a/internal/test/helpers.go b/internal/test/helpers.go index efcb8bec9..a2e0b6835 100644 --- a/internal/test/helpers.go +++ b/internal/test/helpers.go @@ -245,10 +245,11 @@ func SetupCreateUserDeviceWithDeviceID(t *testing.T, testUserID string, deviceID return ud } -func SetupCreateAftermarketDevice(t *testing.T, userID, unitID string, deviceID *string, pdb db.Store) *models.AftermarketDevice { +func SetupCreateAftermarketDevice(t *testing.T, userID string, bytes []byte, unitID string, deviceID *string, pdb db.Store) *models.AftermarketDevice { amd := models.AftermarketDevice{ - Serial: unitID, - UserID: null.StringFrom(userID), + EthereumAddress: bytes, // pkey + Serial: unitID, + UserID: null.StringFrom(userID), } if deviceID != nil { amdMD := map[string]any{"autoPiDeviceId": *deviceID} @@ -264,7 +265,7 @@ func SetupCreateMintedAftermarketDevice(t *testing.T, userID, unitID string, tok Serial: unitID, UserID: null.StringFrom(userID), TokenID: types.NewNullDecimal(new(decimal.Big).SetBigMantScale(tokenID, 0)), - EthereumAddress: null.BytesFrom(addr.Bytes()), + EthereumAddress: addr.Bytes(), } if deviceID != nil { amdMD := map[string]any{"autoPiDeviceId": *deviceID} diff --git a/migrations/20230719150333_aftermarket_pkey_change_add_make.sql b/migrations/20230719150333_aftermarket_pkey_change_add_make.sql new file mode 100644 index 000000000..b508973e4 --- /dev/null +++ b/migrations/20230719150333_aftermarket_pkey_change_add_make.sql @@ -0,0 +1,49 @@ +-- +goose Up +-- +goose StatementBegin +SELECT 'up SQL query'; +SET search_path = devices_api, public; +alter table aftermarket_devices add column device_manufacturer_token_id numeric(78) + CHECK (device_manufacturer_token_id >= 0 AND device_manufacturer_token_id < 2^256); + +-- delete data that won't work for this phase, address cannot be null +delete from user_device_api_integrations where integration_id = '27qftVRWQYpVDcO5DltO5Ojbjxk' + and user_device_id in ( + select user_device_id from user_device_api_integrations inner join aftermarket_devices ad on ad.serial = user_device_api_integrations.serial + where ad.ethereum_address is null + ); +delete from aftermarket_devices where ethereum_address is null; +alter table aftermarket_devices alter column ethereum_address set not null; + +-- drop fkey relations +ALTER TABLE user_device_api_integrations + DROP CONSTRAINT user_device_api_integrations_autopi_units; + +ALTER TABLE autopi_jobs + DROP CONSTRAINT autopi_jobs_autopi_units; + +-- drop the pkey and recreate index on serial +alter table aftermarket_devices drop constraint autopi_units_pkey; +create unique index aftermarket_devices_serial_idx on aftermarket_devices (serial) ; + +ALTER TABLE aftermarket_devices ADD PRIMARY KEY (ethereum_address); + +-- recreate fkey relations, but keep relation to serial since we use it as the autopi unit id for other operations +alter table user_device_api_integrations + add constraint user_device_api_integrations_aftermarket_devices + foreign key (serial) references aftermarket_devices (serial); +alter table autopi_jobs + add constraint autopi_jobs_aftermarket_devices + foreign key (autopi_unit_id) references aftermarket_devices (serial); + +-- +goose StatementEnd + +-- +goose Down +-- +goose StatementBegin +SELECT 'down SQL query'; +SET search_path = devices_api, public; +alter table aftermarket_devices drop column device_make_token_id; +alter table aftermarket_devices alter column ethereum_address drop not null; +alter table aftermarket_devices drop constraint aftermarket_devices_pkey; +ALTER TABLE aftermarket_devices ADD PRIMARY KEY (serial); + +-- +goose StatementEnd \ No newline at end of file diff --git a/models/aftermarket_devices.go b/models/aftermarket_devices.go index 720fdfc0b..8e2f0abc0 100644 --- a/models/aftermarket_devices.go +++ b/models/aftermarket_devices.go @@ -27,7 +27,7 @@ import ( type AftermarketDevice struct { Serial string `boil:"serial" json:"serial" toml:"serial" yaml:"serial"` UserID null.String `boil:"user_id" json:"user_id,omitempty" toml:"user_id" yaml:"user_id,omitempty"` - EthereumAddress null.Bytes `boil:"ethereum_address" json:"ethereum_address,omitempty" toml:"ethereum_address" yaml:"ethereum_address,omitempty"` + EthereumAddress []byte `boil:"ethereum_address" json:"ethereum_address" toml:"ethereum_address" yaml:"ethereum_address"` CreatedAt time.Time `boil:"created_at" json:"created_at" toml:"created_at" yaml:"created_at"` UpdatedAt time.Time `boil:"updated_at" json:"updated_at" toml:"updated_at" yaml:"updated_at"` TokenID types.NullDecimal `boil:"token_id" json:"token_id,omitempty" toml:"token_id" yaml:"token_id,omitempty"` @@ -38,6 +38,7 @@ type AftermarketDevice struct { VehicleTokenID types.NullDecimal `boil:"vehicle_token_id" json:"vehicle_token_id,omitempty" toml:"vehicle_token_id" yaml:"vehicle_token_id,omitempty"` Beneficiary null.Bytes `boil:"beneficiary" json:"beneficiary,omitempty" toml:"beneficiary" yaml:"beneficiary,omitempty"` Metadata null.JSON `boil:"metadata" json:"metadata,omitempty" toml:"metadata" yaml:"metadata,omitempty"` + DeviceManufacturerTokenID types.NullDecimal `boil:"device_manufacturer_token_id" json:"device_manufacturer_token_id,omitempty" toml:"device_manufacturer_token_id" yaml:"device_manufacturer_token_id,omitempty"` R *aftermarketDeviceR `boil:"-" json:"-" toml:"-" yaml:"-"` L aftermarketDeviceL `boil:"-" json:"-" toml:"-" yaml:"-"` @@ -57,6 +58,7 @@ var AftermarketDeviceColumns = struct { VehicleTokenID string Beneficiary string Metadata string + DeviceManufacturerTokenID string }{ Serial: "serial", UserID: "user_id", @@ -71,6 +73,7 @@ var AftermarketDeviceColumns = struct { VehicleTokenID: "vehicle_token_id", Beneficiary: "beneficiary", Metadata: "metadata", + DeviceManufacturerTokenID: "device_manufacturer_token_id", } var AftermarketDeviceTableColumns = struct { @@ -87,6 +90,7 @@ var AftermarketDeviceTableColumns = struct { VehicleTokenID string Beneficiary string Metadata string + DeviceManufacturerTokenID string }{ Serial: "aftermarket_devices.serial", UserID: "aftermarket_devices.user_id", @@ -101,6 +105,7 @@ var AftermarketDeviceTableColumns = struct { VehicleTokenID: "aftermarket_devices.vehicle_token_id", Beneficiary: "aftermarket_devices.beneficiary", Metadata: "aftermarket_devices.metadata", + DeviceManufacturerTokenID: "aftermarket_devices.device_manufacturer_token_id", } // Generated where @@ -166,29 +171,14 @@ func (w whereHelpernull_String) NIN(slice []string) qm.QueryMod { func (w whereHelpernull_String) IsNull() qm.QueryMod { return qmhelper.WhereIsNull(w.field) } func (w whereHelpernull_String) IsNotNull() qm.QueryMod { return qmhelper.WhereIsNotNull(w.field) } -type whereHelpernull_Bytes struct{ field string } +type whereHelper__byte struct{ field string } -func (w whereHelpernull_Bytes) EQ(x null.Bytes) qm.QueryMod { - return qmhelper.WhereNullEQ(w.field, false, x) -} -func (w whereHelpernull_Bytes) NEQ(x null.Bytes) qm.QueryMod { - return qmhelper.WhereNullEQ(w.field, true, x) -} -func (w whereHelpernull_Bytes) LT(x null.Bytes) qm.QueryMod { - return qmhelper.Where(w.field, qmhelper.LT, x) -} -func (w whereHelpernull_Bytes) LTE(x null.Bytes) qm.QueryMod { - return qmhelper.Where(w.field, qmhelper.LTE, x) -} -func (w whereHelpernull_Bytes) GT(x null.Bytes) qm.QueryMod { - return qmhelper.Where(w.field, qmhelper.GT, x) -} -func (w whereHelpernull_Bytes) GTE(x null.Bytes) qm.QueryMod { - return qmhelper.Where(w.field, qmhelper.GTE, x) -} - -func (w whereHelpernull_Bytes) IsNull() qm.QueryMod { return qmhelper.WhereIsNull(w.field) } -func (w whereHelpernull_Bytes) IsNotNull() qm.QueryMod { return qmhelper.WhereIsNotNull(w.field) } +func (w whereHelper__byte) EQ(x []byte) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.EQ, x) } +func (w whereHelper__byte) NEQ(x []byte) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.NEQ, x) } +func (w whereHelper__byte) LT(x []byte) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.LT, x) } +func (w whereHelper__byte) LTE(x []byte) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.LTE, x) } +func (w whereHelper__byte) GT(x []byte) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.GT, x) } +func (w whereHelper__byte) GTE(x []byte) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.GTE, x) } type whereHelpertime_Time struct{ field string } @@ -237,6 +227,30 @@ func (w whereHelpertypes_NullDecimal) IsNotNull() qm.QueryMod { return qmhelper.WhereIsNotNull(w.field) } +type whereHelpernull_Bytes struct{ field string } + +func (w whereHelpernull_Bytes) EQ(x null.Bytes) qm.QueryMod { + return qmhelper.WhereNullEQ(w.field, false, x) +} +func (w whereHelpernull_Bytes) NEQ(x null.Bytes) qm.QueryMod { + return qmhelper.WhereNullEQ(w.field, true, x) +} +func (w whereHelpernull_Bytes) LT(x null.Bytes) qm.QueryMod { + return qmhelper.Where(w.field, qmhelper.LT, x) +} +func (w whereHelpernull_Bytes) LTE(x null.Bytes) qm.QueryMod { + return qmhelper.Where(w.field, qmhelper.LTE, x) +} +func (w whereHelpernull_Bytes) GT(x null.Bytes) qm.QueryMod { + return qmhelper.Where(w.field, qmhelper.GT, x) +} +func (w whereHelpernull_Bytes) GTE(x null.Bytes) qm.QueryMod { + return qmhelper.Where(w.field, qmhelper.GTE, x) +} + +func (w whereHelpernull_Bytes) IsNull() qm.QueryMod { return qmhelper.WhereIsNull(w.field) } +func (w whereHelpernull_Bytes) IsNotNull() qm.QueryMod { return qmhelper.WhereIsNotNull(w.field) } + type whereHelpernull_JSON struct{ field string } func (w whereHelpernull_JSON) EQ(x null.JSON) qm.QueryMod { @@ -264,7 +278,7 @@ func (w whereHelpernull_JSON) IsNotNull() qm.QueryMod { return qmhelper.WhereIsN var AftermarketDeviceWhere = struct { Serial whereHelperstring UserID whereHelpernull_String - EthereumAddress whereHelpernull_Bytes + EthereumAddress whereHelper__byte CreatedAt whereHelpertime_Time UpdatedAt whereHelpertime_Time TokenID whereHelpertypes_NullDecimal @@ -275,10 +289,11 @@ var AftermarketDeviceWhere = struct { VehicleTokenID whereHelpertypes_NullDecimal Beneficiary whereHelpernull_Bytes Metadata whereHelpernull_JSON + DeviceManufacturerTokenID whereHelpertypes_NullDecimal }{ Serial: whereHelperstring{field: "\"devices_api\".\"aftermarket_devices\".\"serial\""}, UserID: whereHelpernull_String{field: "\"devices_api\".\"aftermarket_devices\".\"user_id\""}, - EthereumAddress: whereHelpernull_Bytes{field: "\"devices_api\".\"aftermarket_devices\".\"ethereum_address\""}, + EthereumAddress: whereHelper__byte{field: "\"devices_api\".\"aftermarket_devices\".\"ethereum_address\""}, CreatedAt: whereHelpertime_Time{field: "\"devices_api\".\"aftermarket_devices\".\"created_at\""}, UpdatedAt: whereHelpertime_Time{field: "\"devices_api\".\"aftermarket_devices\".\"updated_at\""}, TokenID: whereHelpertypes_NullDecimal{field: "\"devices_api\".\"aftermarket_devices\".\"token_id\""}, @@ -289,6 +304,7 @@ var AftermarketDeviceWhere = struct { VehicleTokenID: whereHelpertypes_NullDecimal{field: "\"devices_api\".\"aftermarket_devices\".\"vehicle_token_id\""}, Beneficiary: whereHelpernull_Bytes{field: "\"devices_api\".\"aftermarket_devices\".\"beneficiary\""}, Metadata: whereHelpernull_JSON{field: "\"devices_api\".\"aftermarket_devices\".\"metadata\""}, + DeviceManufacturerTokenID: whereHelpertypes_NullDecimal{field: "\"devices_api\".\"aftermarket_devices\".\"device_manufacturer_token_id\""}, } // AftermarketDeviceRels is where relationship names are stored. @@ -369,10 +385,10 @@ func (r *aftermarketDeviceR) GetSerialUserDeviceAPIIntegrations() UserDeviceAPII type aftermarketDeviceL struct{} var ( - aftermarketDeviceAllColumns = []string{"serial", "user_id", "ethereum_address", "created_at", "updated_at", "token_id", "claim_meta_transaction_request_id", "owner_address", "pair_request_id", "unpair_request_id", "vehicle_token_id", "beneficiary", "metadata"} - aftermarketDeviceColumnsWithoutDefault = []string{"serial"} - aftermarketDeviceColumnsWithDefault = []string{"user_id", "ethereum_address", "created_at", "updated_at", "token_id", "claim_meta_transaction_request_id", "owner_address", "pair_request_id", "unpair_request_id", "vehicle_token_id", "beneficiary", "metadata"} - aftermarketDevicePrimaryKeyColumns = []string{"serial"} + aftermarketDeviceAllColumns = []string{"serial", "user_id", "ethereum_address", "created_at", "updated_at", "token_id", "claim_meta_transaction_request_id", "owner_address", "pair_request_id", "unpair_request_id", "vehicle_token_id", "beneficiary", "metadata", "device_manufacturer_token_id"} + aftermarketDeviceColumnsWithoutDefault = []string{"serial", "ethereum_address"} + aftermarketDeviceColumnsWithDefault = []string{"user_id", "created_at", "updated_at", "token_id", "claim_meta_transaction_request_id", "owner_address", "pair_request_id", "unpair_request_id", "vehicle_token_id", "beneficiary", "metadata", "device_manufacturer_token_id"} + aftermarketDevicePrimaryKeyColumns = []string{"ethereum_address"} aftermarketDeviceGeneratedColumns = []string{} ) @@ -1466,7 +1482,7 @@ func (o *AftermarketDevice) SetClaimMetaTransactionRequest(ctx context.Context, strmangle.SetParamNames("\"", "\"", 1, []string{"claim_meta_transaction_request_id"}), strmangle.WhereClause("\"", "\"", 2, aftermarketDevicePrimaryKeyColumns), ) - values := []interface{}{related.ID, o.Serial} + values := []interface{}{related.ID, o.EthereumAddress} if boil.IsDebug(ctx) { writer := boil.DebugWriterFrom(ctx) @@ -1535,7 +1551,7 @@ func (o *AftermarketDevice) SetPairRequest(ctx context.Context, exec boil.Contex strmangle.SetParamNames("\"", "\"", 1, []string{"pair_request_id"}), strmangle.WhereClause("\"", "\"", 2, aftermarketDevicePrimaryKeyColumns), ) - values := []interface{}{related.ID, o.Serial} + values := []interface{}{related.ID, o.EthereumAddress} if boil.IsDebug(ctx) { writer := boil.DebugWriterFrom(ctx) @@ -1604,7 +1620,7 @@ func (o *AftermarketDevice) SetUnpairRequest(ctx context.Context, exec boil.Cont strmangle.SetParamNames("\"", "\"", 1, []string{"unpair_request_id"}), strmangle.WhereClause("\"", "\"", 2, aftermarketDevicePrimaryKeyColumns), ) - values := []interface{}{related.ID, o.Serial} + values := []interface{}{related.ID, o.EthereumAddress} if boil.IsDebug(ctx) { writer := boil.DebugWriterFrom(ctx) @@ -1673,7 +1689,7 @@ func (o *AftermarketDevice) SetVehicleToken(ctx context.Context, exec boil.Conte strmangle.SetParamNames("\"", "\"", 1, []string{"vehicle_token_id"}), strmangle.WhereClause("\"", "\"", 2, aftermarketDevicePrimaryKeyColumns), ) - values := []interface{}{related.TokenID, o.Serial} + values := []interface{}{related.TokenID, o.EthereumAddress} if boil.IsDebug(ctx) { writer := boil.DebugWriterFrom(ctx) @@ -1993,7 +2009,7 @@ func AftermarketDevices(mods ...qm.QueryMod) aftermarketDeviceQuery { // FindAftermarketDevice retrieves a single record by ID with an executor. // If selectCols is empty Find will return all columns. -func FindAftermarketDevice(ctx context.Context, exec boil.ContextExecutor, serial string, selectCols ...string) (*AftermarketDevice, error) { +func FindAftermarketDevice(ctx context.Context, exec boil.ContextExecutor, ethereumAddress []byte, selectCols ...string) (*AftermarketDevice, error) { aftermarketDeviceObj := &AftermarketDevice{} sel := "*" @@ -2001,10 +2017,10 @@ func FindAftermarketDevice(ctx context.Context, exec boil.ContextExecutor, seria sel = strings.Join(strmangle.IdentQuoteSlice(dialect.LQ, dialect.RQ, selectCols), ",") } query := fmt.Sprintf( - "select %s from \"devices_api\".\"aftermarket_devices\" where \"serial\"=$1", sel, + "select %s from \"devices_api\".\"aftermarket_devices\" where \"ethereum_address\"=$1", sel, ) - q := queries.Raw(query, serial) + q := queries.Raw(query, ethereumAddress) err := q.Bind(ctx, exec, aftermarketDeviceObj) if err != nil { @@ -2380,7 +2396,7 @@ func (o *AftermarketDevice) Delete(ctx context.Context, exec boil.ContextExecuto } args := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), aftermarketDevicePrimaryKeyMapping) - sql := "DELETE FROM \"devices_api\".\"aftermarket_devices\" WHERE \"serial\"=$1" + sql := "DELETE FROM \"devices_api\".\"aftermarket_devices\" WHERE \"ethereum_address\"=$1" if boil.IsDebug(ctx) { writer := boil.DebugWriterFrom(ctx) @@ -2477,7 +2493,7 @@ func (o AftermarketDeviceSlice) DeleteAll(ctx context.Context, exec boil.Context // Reload refetches the object from the database // using the primary keys with an executor. func (o *AftermarketDevice) Reload(ctx context.Context, exec boil.ContextExecutor) error { - ret, err := FindAftermarketDevice(ctx, exec, o.Serial) + ret, err := FindAftermarketDevice(ctx, exec, o.EthereumAddress) if err != nil { return err } @@ -2516,16 +2532,16 @@ func (o *AftermarketDeviceSlice) ReloadAll(ctx context.Context, exec boil.Contex } // AftermarketDeviceExists checks if the AftermarketDevice row exists. -func AftermarketDeviceExists(ctx context.Context, exec boil.ContextExecutor, serial string) (bool, error) { +func AftermarketDeviceExists(ctx context.Context, exec boil.ContextExecutor, ethereumAddress []byte) (bool, error) { var exists bool - sql := "select exists(select 1 from \"devices_api\".\"aftermarket_devices\" where \"serial\"=$1 limit 1)" + sql := "select exists(select 1 from \"devices_api\".\"aftermarket_devices\" where \"ethereum_address\"=$1 limit 1)" if boil.IsDebug(ctx) { writer := boil.DebugWriterFrom(ctx) fmt.Fprintln(writer, sql) - fmt.Fprintln(writer, serial) + fmt.Fprintln(writer, ethereumAddress) } - row := exec.QueryRowContext(ctx, sql, serial) + row := exec.QueryRowContext(ctx, sql, ethereumAddress) err := row.Scan(&exists) if err != nil { @@ -2537,5 +2553,5 @@ func AftermarketDeviceExists(ctx context.Context, exec boil.ContextExecutor, ser // Exists checks if the AftermarketDevice row exists. func (o *AftermarketDevice) Exists(ctx context.Context, exec boil.ContextExecutor) (bool, error) { - return AftermarketDeviceExists(ctx, exec, o.Serial) + return AftermarketDeviceExists(ctx, exec, o.EthereumAddress) } diff --git a/models/dcn.go b/models/dcn.go index 748d9fe7d..d6576c804 100644 --- a/models/dcn.go +++ b/models/dcn.go @@ -74,15 +74,6 @@ var DCNTableColumns = struct { // Generated where -type whereHelper__byte struct{ field string } - -func (w whereHelper__byte) EQ(x []byte) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.EQ, x) } -func (w whereHelper__byte) NEQ(x []byte) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.NEQ, x) } -func (w whereHelper__byte) LT(x []byte) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.LT, x) } -func (w whereHelper__byte) LTE(x []byte) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.LTE, x) } -func (w whereHelper__byte) GT(x []byte) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.GT, x) } -func (w whereHelper__byte) GTE(x []byte) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.GTE, x) } - var DCNWhere = struct { NFTNodeID whereHelper__byte OwnerAddress whereHelpernull_Bytes diff --git a/models/external_vin_data.go b/models/external_vin_data.go index 10354e305..396edafb1 100644 --- a/models/external_vin_data.go +++ b/models/external_vin_data.go @@ -199,14 +199,10 @@ var ExternalVinDatumWhere = struct { // ExternalVinDatumRels is where relationship names are stored. var ExternalVinDatumRels = struct { - UserDevice string -}{ - UserDevice: "UserDevice", -} +}{} // externalVinDatumR is where relationships are stored. type externalVinDatumR struct { - UserDevice *UserDevice `boil:"UserDevice" json:"UserDevice" toml:"UserDevice" yaml:"UserDevice"` } // NewStruct creates a new relationship struct @@ -214,13 +210,6 @@ func (*externalVinDatumR) NewStruct() *externalVinDatumR { return &externalVinDatumR{} } -func (r *externalVinDatumR) GetUserDevice() *UserDevice { - if r == nil { - return nil - } - return r.UserDevice -} - // externalVinDatumL is where Load methods for each relationship are stored. type externalVinDatumL struct{} @@ -510,221 +499,6 @@ func (q externalVinDatumQuery) Exists(ctx context.Context, exec boil.ContextExec return count > 0, nil } -// UserDevice pointed to by the foreign key. -func (o *ExternalVinDatum) UserDevice(mods ...qm.QueryMod) userDeviceQuery { - queryMods := []qm.QueryMod{ - qm.Where("\"id\" = ?", o.UserDeviceID), - } - - queryMods = append(queryMods, mods...) - - return UserDevices(queryMods...) -} - -// LoadUserDevice allows an eager lookup of values, cached into the -// loaded structs of the objects. This is for an N-1 relationship. -func (externalVinDatumL) LoadUserDevice(ctx context.Context, e boil.ContextExecutor, singular bool, maybeExternalVinDatum interface{}, mods queries.Applicator) error { - var slice []*ExternalVinDatum - var object *ExternalVinDatum - - if singular { - var ok bool - object, ok = maybeExternalVinDatum.(*ExternalVinDatum) - if !ok { - object = new(ExternalVinDatum) - ok = queries.SetFromEmbeddedStruct(&object, &maybeExternalVinDatum) - if !ok { - return errors.New(fmt.Sprintf("failed to set %T from embedded struct %T", object, maybeExternalVinDatum)) - } - } - } else { - s, ok := maybeExternalVinDatum.(*[]*ExternalVinDatum) - if ok { - slice = *s - } else { - ok = queries.SetFromEmbeddedStruct(&slice, maybeExternalVinDatum) - if !ok { - return errors.New(fmt.Sprintf("failed to set %T from embedded struct %T", slice, maybeExternalVinDatum)) - } - } - } - - args := make([]interface{}, 0, 1) - if singular { - if object.R == nil { - object.R = &externalVinDatumR{} - } - if !queries.IsNil(object.UserDeviceID) { - args = append(args, object.UserDeviceID) - } - - } else { - Outer: - for _, obj := range slice { - if obj.R == nil { - obj.R = &externalVinDatumR{} - } - - for _, a := range args { - if queries.Equal(a, obj.UserDeviceID) { - continue Outer - } - } - - if !queries.IsNil(obj.UserDeviceID) { - args = append(args, obj.UserDeviceID) - } - - } - } - - if len(args) == 0 { - return nil - } - - query := NewQuery( - qm.From(`devices_api.user_devices`), - qm.WhereIn(`devices_api.user_devices.id in ?`, args...), - ) - if mods != nil { - mods.Apply(query) - } - - results, err := query.QueryContext(ctx, e) - if err != nil { - return errors.Wrap(err, "failed to eager load UserDevice") - } - - var resultSlice []*UserDevice - if err = queries.Bind(results, &resultSlice); err != nil { - return errors.Wrap(err, "failed to bind eager loaded slice UserDevice") - } - - if err = results.Close(); err != nil { - return errors.Wrap(err, "failed to close results of eager load for user_devices") - } - if err = results.Err(); err != nil { - return errors.Wrap(err, "error occurred during iteration of eager loaded relations for user_devices") - } - - if len(userDeviceAfterSelectHooks) != 0 { - for _, obj := range resultSlice { - if err := obj.doAfterSelectHooks(ctx, e); err != nil { - return err - } - } - } - - if len(resultSlice) == 0 { - return nil - } - - if singular { - foreign := resultSlice[0] - object.R.UserDevice = foreign - if foreign.R == nil { - foreign.R = &userDeviceR{} - } - foreign.R.ExternalVinData = append(foreign.R.ExternalVinData, object) - return nil - } - - for _, local := range slice { - for _, foreign := range resultSlice { - if queries.Equal(local.UserDeviceID, foreign.ID) { - local.R.UserDevice = foreign - if foreign.R == nil { - foreign.R = &userDeviceR{} - } - foreign.R.ExternalVinData = append(foreign.R.ExternalVinData, local) - break - } - } - } - - return nil -} - -// SetUserDevice of the externalVinDatum to the related item. -// Sets o.R.UserDevice to related. -// Adds o to related.R.ExternalVinData. -func (o *ExternalVinDatum) SetUserDevice(ctx context.Context, exec boil.ContextExecutor, insert bool, related *UserDevice) error { - var err error - if insert { - if err = related.Insert(ctx, exec, boil.Infer()); err != nil { - return errors.Wrap(err, "failed to insert into foreign table") - } - } - - updateQuery := fmt.Sprintf( - "UPDATE \"devices_api\".\"external_vin_data\" SET %s WHERE %s", - strmangle.SetParamNames("\"", "\"", 1, []string{"user_device_id"}), - strmangle.WhereClause("\"", "\"", 2, externalVinDatumPrimaryKeyColumns), - ) - values := []interface{}{related.ID, o.ID} - - if boil.IsDebug(ctx) { - writer := boil.DebugWriterFrom(ctx) - fmt.Fprintln(writer, updateQuery) - fmt.Fprintln(writer, values) - } - if _, err = exec.ExecContext(ctx, updateQuery, values...); err != nil { - return errors.Wrap(err, "failed to update local table") - } - - queries.Assign(&o.UserDeviceID, related.ID) - if o.R == nil { - o.R = &externalVinDatumR{ - UserDevice: related, - } - } else { - o.R.UserDevice = related - } - - if related.R == nil { - related.R = &userDeviceR{ - ExternalVinData: ExternalVinDatumSlice{o}, - } - } else { - related.R.ExternalVinData = append(related.R.ExternalVinData, o) - } - - return nil -} - -// RemoveUserDevice relationship. -// Sets o.R.UserDevice to nil. -// Removes o from all passed in related items' relationships struct. -func (o *ExternalVinDatum) RemoveUserDevice(ctx context.Context, exec boil.ContextExecutor, related *UserDevice) error { - var err error - - queries.SetScanner(&o.UserDeviceID, nil) - if _, err = o.Update(ctx, exec, boil.Whitelist("user_device_id")); err != nil { - return errors.Wrap(err, "failed to update local table") - } - - if o.R != nil { - o.R.UserDevice = nil - } - if related == nil || related.R == nil { - return nil - } - - for i, ri := range related.R.ExternalVinData { - if queries.Equal(o.UserDeviceID, ri.UserDeviceID) { - continue - } - - ln := len(related.R.ExternalVinData) - if ln > 1 && i < ln-1 { - related.R.ExternalVinData[i] = related.R.ExternalVinData[ln-1] - } - related.R.ExternalVinData = related.R.ExternalVinData[:ln-1] - break - } - return nil -} - // ExternalVinData retrieves all the records using an executor. func ExternalVinData(mods ...qm.QueryMod) externalVinDatumQuery { mods = append(mods, qm.From("\"devices_api\".\"external_vin_data\"")) diff --git a/models/meta_transaction_requests.go b/models/meta_transaction_requests.go index 5520a4d86..2daaa110f 100644 --- a/models/meta_transaction_requests.go +++ b/models/meta_transaction_requests.go @@ -1227,7 +1227,7 @@ func (o *MetaTransactionRequest) SetClaimMetaTransactionRequestAftermarketDevice strmangle.SetParamNames("\"", "\"", 1, []string{"claim_meta_transaction_request_id"}), strmangle.WhereClause("\"", "\"", 2, aftermarketDevicePrimaryKeyColumns), ) - values := []interface{}{o.ID, related.Serial} + values := []interface{}{o.ID, related.EthereumAddress} if boil.IsDebug(ctx) { writer := boil.DebugWriterFrom(ctx) @@ -1301,7 +1301,7 @@ func (o *MetaTransactionRequest) SetPairRequestAftermarketDevice(ctx context.Con strmangle.SetParamNames("\"", "\"", 1, []string{"pair_request_id"}), strmangle.WhereClause("\"", "\"", 2, aftermarketDevicePrimaryKeyColumns), ) - values := []interface{}{o.ID, related.Serial} + values := []interface{}{o.ID, related.EthereumAddress} if boil.IsDebug(ctx) { writer := boil.DebugWriterFrom(ctx) @@ -1375,7 +1375,7 @@ func (o *MetaTransactionRequest) SetUnpairRequestAftermarketDevice(ctx context.C strmangle.SetParamNames("\"", "\"", 1, []string{"unpair_request_id"}), strmangle.WhereClause("\"", "\"", 2, aftermarketDevicePrimaryKeyColumns), ) - values := []interface{}{o.ID, related.Serial} + values := []interface{}{o.ID, related.EthereumAddress} if boil.IsDebug(ctx) { writer := boil.DebugWriterFrom(ctx) diff --git a/models/psql_upsert.go b/models/psql_upsert.go index a7c18b85c..1817cc984 100644 --- a/models/psql_upsert.go +++ b/models/psql_upsert.go @@ -42,9 +42,6 @@ func buildUpsertQueryPostgres(dia drivers.Dialect, tableName string, updateOnCon buf.WriteString(") DO UPDATE SET ") for i, v := range update { - if len(v) == 0 { - continue - } if i != 0 { buf.WriteByte(',') } diff --git a/models/user_devices.go b/models/user_devices.go index e10d5c184..db2269d01 100644 --- a/models/user_devices.go +++ b/models/user_devices.go @@ -149,7 +149,6 @@ var UserDeviceRels = struct { AutopiJobs string DeviceCommandRequests string ErrorCodeQueries string - ExternalVinData string UserDeviceAPIIntegrations string UserDeviceData string UserDeviceToGeofences string @@ -158,7 +157,6 @@ var UserDeviceRels = struct { AutopiJobs: "AutopiJobs", DeviceCommandRequests: "DeviceCommandRequests", ErrorCodeQueries: "ErrorCodeQueries", - ExternalVinData: "ExternalVinData", UserDeviceAPIIntegrations: "UserDeviceAPIIntegrations", UserDeviceData: "UserDeviceData", UserDeviceToGeofences: "UserDeviceToGeofences", @@ -170,7 +168,6 @@ type userDeviceR struct { AutopiJobs AutopiJobSlice `boil:"AutopiJobs" json:"AutopiJobs" toml:"AutopiJobs" yaml:"AutopiJobs"` DeviceCommandRequests DeviceCommandRequestSlice `boil:"DeviceCommandRequests" json:"DeviceCommandRequests" toml:"DeviceCommandRequests" yaml:"DeviceCommandRequests"` ErrorCodeQueries ErrorCodeQuerySlice `boil:"ErrorCodeQueries" json:"ErrorCodeQueries" toml:"ErrorCodeQueries" yaml:"ErrorCodeQueries"` - ExternalVinData ExternalVinDatumSlice `boil:"ExternalVinData" json:"ExternalVinData" toml:"ExternalVinData" yaml:"ExternalVinData"` UserDeviceAPIIntegrations UserDeviceAPIIntegrationSlice `boil:"UserDeviceAPIIntegrations" json:"UserDeviceAPIIntegrations" toml:"UserDeviceAPIIntegrations" yaml:"UserDeviceAPIIntegrations"` UserDeviceData UserDeviceDatumSlice `boil:"UserDeviceData" json:"UserDeviceData" toml:"UserDeviceData" yaml:"UserDeviceData"` UserDeviceToGeofences UserDeviceToGeofenceSlice `boil:"UserDeviceToGeofences" json:"UserDeviceToGeofences" toml:"UserDeviceToGeofences" yaml:"UserDeviceToGeofences"` @@ -209,13 +206,6 @@ func (r *userDeviceR) GetErrorCodeQueries() ErrorCodeQuerySlice { return r.ErrorCodeQueries } -func (r *userDeviceR) GetExternalVinData() ExternalVinDatumSlice { - if r == nil { - return nil - } - return r.ExternalVinData -} - func (r *userDeviceR) GetUserDeviceAPIIntegrations() UserDeviceAPIIntegrationSlice { if r == nil { return nil @@ -579,20 +569,6 @@ func (o *UserDevice) ErrorCodeQueries(mods ...qm.QueryMod) errorCodeQueryQuery { return ErrorCodeQueries(queryMods...) } -// ExternalVinData retrieves all the external_vin_datum's ExternalVinData with an executor. -func (o *UserDevice) ExternalVinData(mods ...qm.QueryMod) externalVinDatumQuery { - var queryMods []qm.QueryMod - if len(mods) != 0 { - queryMods = append(queryMods, mods...) - } - - queryMods = append(queryMods, - qm.Where("\"devices_api\".\"external_vin_data\".\"user_device_id\"=?", o.ID), - ) - - return ExternalVinData(queryMods...) -} - // UserDeviceAPIIntegrations retrieves all the user_device_api_integration's UserDeviceAPIIntegrations with an executor. func (o *UserDevice) UserDeviceAPIIntegrations(mods ...qm.QueryMod) userDeviceAPIIntegrationQuery { var queryMods []qm.QueryMod @@ -1094,120 +1070,6 @@ func (userDeviceL) LoadErrorCodeQueries(ctx context.Context, e boil.ContextExecu return nil } -// LoadExternalVinData allows an eager lookup of values, cached into the -// loaded structs of the objects. This is for a 1-M or N-M relationship. -func (userDeviceL) LoadExternalVinData(ctx context.Context, e boil.ContextExecutor, singular bool, maybeUserDevice interface{}, mods queries.Applicator) error { - var slice []*UserDevice - var object *UserDevice - - if singular { - var ok bool - object, ok = maybeUserDevice.(*UserDevice) - if !ok { - object = new(UserDevice) - ok = queries.SetFromEmbeddedStruct(&object, &maybeUserDevice) - if !ok { - return errors.New(fmt.Sprintf("failed to set %T from embedded struct %T", object, maybeUserDevice)) - } - } - } else { - s, ok := maybeUserDevice.(*[]*UserDevice) - if ok { - slice = *s - } else { - ok = queries.SetFromEmbeddedStruct(&slice, maybeUserDevice) - if !ok { - return errors.New(fmt.Sprintf("failed to set %T from embedded struct %T", slice, maybeUserDevice)) - } - } - } - - args := make([]interface{}, 0, 1) - if singular { - if object.R == nil { - object.R = &userDeviceR{} - } - args = append(args, object.ID) - } else { - Outer: - for _, obj := range slice { - if obj.R == nil { - obj.R = &userDeviceR{} - } - - for _, a := range args { - if queries.Equal(a, obj.ID) { - continue Outer - } - } - - args = append(args, obj.ID) - } - } - - if len(args) == 0 { - return nil - } - - query := NewQuery( - qm.From(`devices_api.external_vin_data`), - qm.WhereIn(`devices_api.external_vin_data.user_device_id in ?`, args...), - ) - if mods != nil { - mods.Apply(query) - } - - results, err := query.QueryContext(ctx, e) - if err != nil { - return errors.Wrap(err, "failed to eager load external_vin_data") - } - - var resultSlice []*ExternalVinDatum - if err = queries.Bind(results, &resultSlice); err != nil { - return errors.Wrap(err, "failed to bind eager loaded slice external_vin_data") - } - - if err = results.Close(); err != nil { - return errors.Wrap(err, "failed to close results in eager load on external_vin_data") - } - if err = results.Err(); err != nil { - return errors.Wrap(err, "error occurred during iteration of eager loaded relations for external_vin_data") - } - - if len(externalVinDatumAfterSelectHooks) != 0 { - for _, obj := range resultSlice { - if err := obj.doAfterSelectHooks(ctx, e); err != nil { - return err - } - } - } - if singular { - object.R.ExternalVinData = resultSlice - for _, foreign := range resultSlice { - if foreign.R == nil { - foreign.R = &externalVinDatumR{} - } - foreign.R.UserDevice = object - } - return nil - } - - for _, foreign := range resultSlice { - for _, local := range slice { - if queries.Equal(local.ID, foreign.UserDeviceID) { - local.R.ExternalVinData = append(local.R.ExternalVinData, foreign) - if foreign.R == nil { - foreign.R = &externalVinDatumR{} - } - foreign.R.UserDevice = local - break - } - } - } - - return nil -} - // LoadUserDeviceAPIIntegrations allows an eager lookup of values, cached into the // loaded structs of the objects. This is for a 1-M or N-M relationship. func (userDeviceL) LoadUserDeviceAPIIntegrations(ctx context.Context, e boil.ContextExecutor, singular bool, maybeUserDevice interface{}, mods queries.Applicator) error { @@ -1857,133 +1719,6 @@ func (o *UserDevice) AddErrorCodeQueries(ctx context.Context, exec boil.ContextE return nil } -// AddExternalVinData adds the given related objects to the existing relationships -// of the user_device, optionally inserting them as new records. -// Appends related to o.R.ExternalVinData. -// Sets related.R.UserDevice appropriately. -func (o *UserDevice) AddExternalVinData(ctx context.Context, exec boil.ContextExecutor, insert bool, related ...*ExternalVinDatum) error { - var err error - for _, rel := range related { - if insert { - queries.Assign(&rel.UserDeviceID, o.ID) - if err = rel.Insert(ctx, exec, boil.Infer()); err != nil { - return errors.Wrap(err, "failed to insert into foreign table") - } - } else { - updateQuery := fmt.Sprintf( - "UPDATE \"devices_api\".\"external_vin_data\" SET %s WHERE %s", - strmangle.SetParamNames("\"", "\"", 1, []string{"user_device_id"}), - strmangle.WhereClause("\"", "\"", 2, externalVinDatumPrimaryKeyColumns), - ) - values := []interface{}{o.ID, rel.ID} - - if boil.IsDebug(ctx) { - writer := boil.DebugWriterFrom(ctx) - fmt.Fprintln(writer, updateQuery) - fmt.Fprintln(writer, values) - } - if _, err = exec.ExecContext(ctx, updateQuery, values...); err != nil { - return errors.Wrap(err, "failed to update foreign table") - } - - queries.Assign(&rel.UserDeviceID, o.ID) - } - } - - if o.R == nil { - o.R = &userDeviceR{ - ExternalVinData: related, - } - } else { - o.R.ExternalVinData = append(o.R.ExternalVinData, related...) - } - - for _, rel := range related { - if rel.R == nil { - rel.R = &externalVinDatumR{ - UserDevice: o, - } - } else { - rel.R.UserDevice = o - } - } - return nil -} - -// SetExternalVinData removes all previously related items of the -// user_device replacing them completely with the passed -// in related items, optionally inserting them as new records. -// Sets o.R.UserDevice's ExternalVinData accordingly. -// Replaces o.R.ExternalVinData with related. -// Sets related.R.UserDevice's ExternalVinData accordingly. -func (o *UserDevice) SetExternalVinData(ctx context.Context, exec boil.ContextExecutor, insert bool, related ...*ExternalVinDatum) error { - query := "update \"devices_api\".\"external_vin_data\" set \"user_device_id\" = null where \"user_device_id\" = $1" - values := []interface{}{o.ID} - if boil.IsDebug(ctx) { - writer := boil.DebugWriterFrom(ctx) - fmt.Fprintln(writer, query) - fmt.Fprintln(writer, values) - } - _, err := exec.ExecContext(ctx, query, values...) - if err != nil { - return errors.Wrap(err, "failed to remove relationships before set") - } - - if o.R != nil { - for _, rel := range o.R.ExternalVinData { - queries.SetScanner(&rel.UserDeviceID, nil) - if rel.R == nil { - continue - } - - rel.R.UserDevice = nil - } - o.R.ExternalVinData = nil - } - - return o.AddExternalVinData(ctx, exec, insert, related...) -} - -// RemoveExternalVinData relationships from objects passed in. -// Removes related items from R.ExternalVinData (uses pointer comparison, removal does not keep order) -// Sets related.R.UserDevice. -func (o *UserDevice) RemoveExternalVinData(ctx context.Context, exec boil.ContextExecutor, related ...*ExternalVinDatum) error { - if len(related) == 0 { - return nil - } - - var err error - for _, rel := range related { - queries.SetScanner(&rel.UserDeviceID, nil) - if rel.R != nil { - rel.R.UserDevice = nil - } - if _, err = rel.Update(ctx, exec, boil.Whitelist("user_device_id")); err != nil { - return err - } - } - if o.R == nil { - return nil - } - - for _, rel := range related { - for i, ri := range o.R.ExternalVinData { - if rel != ri { - continue - } - - ln := len(o.R.ExternalVinData) - if ln > 1 && i < ln-1 { - o.R.ExternalVinData[i] = o.R.ExternalVinData[ln-1] - } - o.R.ExternalVinData = o.R.ExternalVinData[:ln-1] - break - } - } - - return nil -} - // AddUserDeviceAPIIntegrations adds the given related objects to the existing relationships // of the user_device, optionally inserting them as new records. // Appends related to o.R.UserDeviceAPIIntegrations. diff --git a/models/vehicle_nfts.go b/models/vehicle_nfts.go index e8526dd61..a1ade1c1d 100644 --- a/models/vehicle_nfts.go +++ b/models/vehicle_nfts.go @@ -1299,7 +1299,7 @@ func (o *VehicleNFT) SetVehicleTokenAftermarketDevice(ctx context.Context, exec strmangle.SetParamNames("\"", "\"", 1, []string{"vehicle_token_id"}), strmangle.WhereClause("\"", "\"", 2, aftermarketDevicePrimaryKeyColumns), ) - values := []interface{}{o.TokenID, related.Serial} + values := []interface{}{o.TokenID, related.EthereumAddress} if boil.IsDebug(ctx) { writer := boil.DebugWriterFrom(ctx)