upsert example

$updated_results = $this->testingFakeConnection->select('faking_table')->fields('faking_table')->condition('id', '1')->execute()->fetchAll();

    $this->assertSame('321', $updated_results[0]->test_field);
  }

  /** * @covers \Drupal\Core\Database\Connection::upsert */
  public function testUpsert(): void {
    $num_records_before = $this->testingFakeConnection->query('SELECT COUNT(*) FROM {faking_table}')->fetchField();

    $upsert = $this->testingFakeConnection->upsert('faking_table')
      ->key('id')
      ->fields(['id', 'test_field']);

    // Upserting a new row.     $upsert->values([
      'id' => '456',
      'test_field' => '444',
    ]);

    // Upserting an existing row.     $upsert->values([
      
$this->attributeRepository->create([$attribute], Context::createDefaultContext());

        static::assertInstanceOf(
            $expectedFieldClass,
            $this->attributeService->getCustomField('test_attr')
        );
    }

    public function testOnlyGetActive(): void
    {
        $id = Uuid::randomHex();
        $this->attributeRepository->upsert([[
            'id' => $id,
            'name' => 'test_attr',
            'active' => false,
            'type' => CustomFieldTypes::TEXT,
        ]], Context::createDefaultContext());

        $actual = $this->attributeService->getCustomField('test_attr');
        static::assertNull($actual);

        $this->attributeRepository->upsert([[
            'id' => $id,
            
/** * @return void * * @throws LockExpiredException when save is called on an expired lock */
    public function save(Key $key)
    {
        $key->reduceLifetime($this->initialTtl);

        try {
            $this->upsert($key$this->initialTtl);
        } catch (WriteException $e) {
            if ($this->isDuplicateKeyException($e)) {
                throw new LockConflictedException('Lock was acquired by someone else.', 0, $e);
            }
            throw new LockAcquiringException('Failed to acquire lock.', 0, $e);
        }

        if ($this->options['gcProbability'] > 0.0 && (1.0 === $this->options['gcProbability'] || (random_int(0, \PHP_INT_MAX) / \PHP_INT_MAX) <= $this->options['gcProbability'])) {
            $this->createTtlIndex();
        }

        
'tax' => ['id' => Uuid::randomHex(), 'taxRate' => 19, 'name' => 'tax'],
                'price' => [['currencyId' => Defaults::CURRENCY, 'gross' => 10, 'net' => 12, 'linked' => false]],
                'stock' => 0,
                'visibilities' => [
                    [
                        'salesChannelId' => $salesChannelId,
                        'visibility' => ProductVisibilityDefinition::VISIBILITY_ALL,
                    ],
                ],
            ],
        ];
        $this->productRepository->upsert($products, Context::createDefaultContext());

        $criteria = new Criteria([$id1$id2]);
        $criteria->addAssociation('seoUrls');
        $products = $this->productRepository->search($criteria, Context::createDefaultContext());

        /** @var ProductEntity $first */
        $first = $products->first();
        /** @var SeoUrlCollection $seoUrls */
        $seoUrls = $first->getSeoUrls();
        static::assertCount(1, $seoUrls);

        
static::assertNotFalse($formattedDate);
                static::assertStringContainsString(
                    sprintf('Date %s', $formattedDate),
                    $rendered->getHtml()
                );
            },
        ];

        yield 'render with different language' => [
            [7],
            function DDocumentGenerateOperation $operation, ContainerInterface $container) use ($documentDate): void {
                $container->get('order.repository')->upsert([[
                    'id' => $operation->getOrderId(),
                    'languageId' => self::$deLanguageId,
                ]], Context::createDefaultContext());

                $criteria = OrderDocumentCriteriaFactory::create([$operation->getOrderId()]);
                /** @var OrderEntity $order */
                $order = $container->get('order.repository')->search($criteria, Context::createDefaultContext())->get($operation->getOrderId());

                $context = clone Context::createDefaultContext();
                $context = $context->assign([
                    'languageIdChain' => array_unique(array_filter([self::$deLanguageId, Context::createDefaultContext()->getLanguageId()])),
                ]);

            [
                'id' => $id,
                'productNumber' => Uuid::randomHex(),
                'stock' => 10,
                'name' => 'Update',
                'price' => [['currencyId' => Defaults::CURRENCY, 'gross' => 12, 'net' => 10, 'linked' => false]],
                'ean' => $filterId,
            ],
        ];

        $this->repository->upsert($data, Context::createDefaultContext());

        /** @var ProductCollection $products */
        $products = $this->repository->search(new Criteria([$id]), Context::createDefaultContext())->getEntities();
        static::assertTrue($products->has($id));

        $product = $products->get($id);

        static::assertSame('Update', $product->getName());
        $currencyPrice = $product->getCurrencyPrice(Defaults::CURRENCY);
        static::assertInstanceOf(Price::class$currencyPrice);
        static::assertSame(12.0, $currencyPrice->getGross());

        
->build()
            )
            ->variant(
                (new ProductBuilder($ids, 'v2'))
                    ->price(100)
                    ->add('customEntityBlogInheritedProducts', [$blog2])
                    ->build()
            )
            ->build();

        $event = $container->get('product.repository')
            ->upsert([$product], Context::createDefaultContext());

        static::assertNotEmpty($event->getPrimaryKeys('product'));
        static::assertNotEmpty($event->getPrimaryKeys('custom_entity_blog'));
        static::assertNotEmpty($event->getPrimaryKeys('custom_entity_blog_inherited_products'));

        static::assertContains($ids->get('inh.blog.1')$event->getPrimaryKeys('custom_entity_blog'));
        static::assertContains($ids->get('inh.blog.2')$event->getPrimaryKeys('custom_entity_blog'));

        $context = Context::createDefaultContext();
        $context->setConsiderInheritance(true);

        
$data = $this->prepareImportExportProfileTestData($num);

        $this->repository->create(array_values($data)$this->context);

        $new_data = array_values($this->prepareImportExportProfileTestData($num, 'xxx'));
        foreach ($data as $id => $value) {
            $new_value = array_pop($new_data);
            $new_value['id'] = $value['id'];
            $data[$id] = $new_value;
        }

        $this->repository->upsert(array_values($data)$this->context);

        $records = $this->connection->fetchAllAssociative(
            'SELECT * FROM import_export_profile'
        );
        $translationRecords = $this->getTranslationRecords();

        static::assertCount($num$records);

        foreach ($records as $record) {
            $expect = $data[$record['id']];
            static::assertEquals($expect['name']$record['name']);
            
/** * @param list<array<string, mixed>> $upsertData * @param list<list<string>> $expectedCodePathPairs */
    protected function assertUpsertViolations(array $upsertData, array $expectedCodePathPairs, bool $addDefaultTranslationCode = true): void
    {
        if ($addDefaultTranslationCode) {
            $upsertData = $this->addDefaultTranslationCodes($upsertData);
        }
        $upsertData = $this->addDefaultLocales($upsertData);
        $this->assertWriteStackViolations(function D) use ($upsertData): void {
            $this->languageRepository->upsert($upsertData$this->defaultContext);
        }$expectedCodePathPairs);
    }

    /** * @param array<array<string, mixed|null>> $ids * @param list<list<string>> $expectedCodePathPairs */
    protected function assertDeleteViolations(array $ids, array $expectedCodePathPairs): void
    {
        $this->assertWriteStackViolations(function D) use ($ids): void {
            $this->languageRepository->delete($ids$this->defaultContext);
        },

    private function createPromotion(array $promotionOverride = []): array
    {
        $promotion = array_merge([
            'id' => $promotionOverride['id'] ?? Uuid::randomHex(),
            'name' => 'Test case promotion',
            'active' => true,
            'useIndividualCodes' => true,
        ]$promotionOverride);

        $this->promotionRepo->upsert([$promotion], Context::createDefaultContext());

        return $promotion;
    }
}
$category = [
            'id' => $parent,
            'name' => 'parent',
            'children' => ['id' => $child1, 'name' => 'child 1'],
        ];

        $context = Context::createDefaultContext();

        $e = null;

        try {
            $this->categoryRepository->upsert([$category]$context);
        } catch (WriteException $e) {
        }

        static::assertInstanceOf(WriteException::class$e);

        static::assertCount(1, $e->getExceptions());
        $first = $e->getExceptions()[0];

        static::assertInstanceOf(ExpectedArrayException::class$first);
        static::assertEquals('/0/children', $first->getPath());
    }

    
'purchasePrices' => [
                [
                    'currencyId' => Defaults::CURRENCY,
                    'gross' => 0,
                    'net' => 0,
                    'linked' => true,
                ],
            ],
        ];

        $productRepo = $this->getContainer()->get('product.repository');
        $affected = $productRepo->upsert([$data], Context::createDefaultContext());

        static::assertNotNull($affected->getEventByEntityName(LanguageDefinition::ENTITY_NAME));

        static::assertNotNull($affected->getEventByEntityName(ProductDefinition::ENTITY_NAME));
        static::assertNotNull($affected->getEventByEntityName(ProductTranslationDefinition::ENTITY_NAME));

        static::assertNotNull($affected->getEventByEntityName(TaxDefinition::ENTITY_NAME));

        static::assertNotNull($affected->getEventByEntityName(ProductManufacturerDefinition::ENTITY_NAME));
        static::assertNotNull($affected->getEventByEntityName(ProductManufacturerTranslationDefinition::ENTITY_NAME));

        

    }

    public function testCreatesHookableEntityUpdate(): void
    {
        $id = Uuid::randomHex();

        /** @var EntityRepository $productRepository */
        $productRepository = $this->getContainer()->get('product.repository');
        $this->insertProduct($id$productRepository);

        $writtenEvent = $productRepository->upsert([
            [
                'id' => $id,
                'stock' => 99,
                'price' => [
                    [
                        'gross' => 200,
                        'net' => 250,
                        'linked' => false,
                        'currencyId' => Defaults::CURRENCY,
                    ],
                ],
            ],
'firstName' => 'Max',
                    'lastName' => 'Mustermann',
                    'street' => 'Ebbinghoff 10',
                    'zipcode' => '48624',
                    'city' => 'Schöppingen',
                ],
            ],
        ];

        $this->getContainer()
            ->get('customer.repository')
            ->upsert([$customer], Context::createDefaultContext());

        return $customerId;
    }
}
$themeData['translations'] = $this->getTranslationsConfiguration($configuration$context);

        $updatedData = $this->updateMediaInConfiguration($theme$configuration$context);

        $themeData = array_merge($themeData$updatedData);

        if (!empty($configuration->getConfigInheritance())) {
            $themeData = $this->addParentTheme($configuration$themeData$context);
        }

        $writtenEvent = $this->themeRepository->upsert([$themeData]$context);

        if (empty($themeData['id'])) {
            $themeData['id'] = current($writtenEvent->getPrimaryKeys(ThemeDefinition::ENTITY_NAME));
        }

        $this->themeRepository->upsert([$themeData]$context);

        if (!empty($themeData['toDeleteMedia'])) {
            $this->themeMediaRepository->delete($themeData['toDeleteMedia']$context);
        }

        
Home | Imprint | This part of the site doesn't use cookies.