Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added the with_foreign_keys parameter to allow disabling the creation of foreign keys #587

Merged
merged 6 commits into from
Sep 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,12 @@ simple_things_entity_audit:
entity_manager: custom
```

If you need to explicitly discard the foreign keys inferred from the audited entities, you can use the `disable_foreign_keys` parameter:
```yaml
simple_things_entity_audit:
disable_foreign_keys: true
```

### Creating new tables

Call the command below to see the new tables in the update schema queue.
Expand Down
12 changes: 12 additions & 0 deletions src/AuditConfiguration.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ class AuditConfiguration
*/
private array $auditedEntityClasses = [];

private bool $disableForeignKeys = false;

/**
* @var string[]
*/
Expand Down Expand Up @@ -79,6 +81,16 @@ public function getTableName(ClassMetadataInfo $metadata)
return $this->getTablePrefix().$tableName.$this->getTableSuffix();
}

public function areForeignKeysDisabled(): bool
{
return $this->disableForeignKeys;
}

public function setDisabledForeignKeys(bool $disabled): void
{
$this->disableForeignKeys = $disabled;
}

/**
* @return string
*/
Expand Down
1 change: 1 addition & 0 deletions src/DependencyInjection/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ public function getConfigTreeBuilder()
->scalarNode('revision_field_name')->defaultValue('rev')->end()
->scalarNode('revision_type_field_name')->defaultValue('revtype')->end()
->scalarNode('revision_table_name')->defaultValue('revisions')->end()
->scalarNode('disable_foreign_keys')->defaultValue(false)->end()
->scalarNode('revision_id_field_type')
->defaultValue(Types::INTEGER)
// NEXT_MAJOR: Use enumNode() instead.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ public function load(array $configs, ContainerBuilder $container): void
'revision_table_name',
'revision_id_field_type',
'global_ignore_columns',
'disable_foreign_keys',
];

foreach ($configurables as $key) {
Expand Down
29 changes: 18 additions & 11 deletions src/EventListener/CreateSchemaListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -119,17 +119,9 @@ public function postGenerateSchemaTable(GenerateSchemaTableEventArgs $eventArgs)
}
}

$revisionForeignKeyName = $this->config->getRevisionFieldName().'_'.md5($revisionTable->getName()).'_fk';
$primaryKey = $revisionsTable->getPrimaryKey();
\assert(null !== $primaryKey);

$revisionTable->addForeignKeyConstraint(
$revisionsTable,
[$this->config->getRevisionFieldName()],
$primaryKey->getColumns(),
[],
$revisionForeignKeyName
);
if (!$this->config->areForeignKeysDisabled()) {
$this->createForeignKeys($revisionTable, $revisionsTable);
}
}

public function postGenerateSchema(GenerateSchemaEventArgs $eventArgs): void
Expand All @@ -142,6 +134,21 @@ public function postGenerateSchema(GenerateSchemaEventArgs $eventArgs): void
}
}

private function createForeignKeys(Table $relatedTable, Table $revisionsTable): void
{
$revisionForeignKeyName = $this->config->getRevisionFieldName().'_'.md5($relatedTable->getName()).'_fk';
$primaryKey = $revisionsTable->getPrimaryKey();
\assert(null !== $primaryKey);

$relatedTable->addForeignKeyConstraint(
$revisionsTable,
[$this->config->getRevisionFieldName()],
$primaryKey->getColumns(),
[],
$revisionForeignKeyName
);
}

/**
* Copies $column to another table. All its options are copied but notnull and autoincrement which are set to false.
*/
Expand Down
5 changes: 4 additions & 1 deletion src/Resources/config/auditable.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,9 @@

->set('simplethings.entityaudit.revision_table_name', null)

->set('simplethings.entityaudit.revision_id_field_type', null);
->set('simplethings.entityaudit.revision_id_field_type', null)

->set('simplethings.entityaudit.disable_foreign_keys', null);

$containerConfigurator->services()
->set('simplethings_entityaudit.manager', AuditManager::class)
Expand Down Expand Up @@ -119,6 +121,7 @@
->set('simplethings_entityaudit.config', AuditConfiguration::class)
->public()
->call('setAuditedEntityClasses', [param('simplethings.entityaudit.audited_entities')])
->call('setDisabledForeignKeys', [param('simplethings.entityaudit.disable_foreign_keys')])
->call('setGlobalIgnoreColumns', [param('simplethings.entityaudit.global_ignore_columns')])
->call('setTablePrefix', [param('simplethings.entityaudit.table_prefix')])
->call('setTableSuffix', [param('simplethings.entityaudit.table_suffix')])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ public function testItRegistersDefaultServices(): void
$this->assertContainerBuilderHasServiceDefinitionWithMethodCall('simplethings_entityaudit.config', 'setRevisionIdFieldType', ['%simplethings.entityaudit.revision_id_field_type%']);
$this->assertContainerBuilderHasServiceDefinitionWithMethodCall('simplethings_entityaudit.config', 'setRevisionFieldName', ['%simplethings.entityaudit.revision_field_name%']);
$this->assertContainerBuilderHasServiceDefinitionWithMethodCall('simplethings_entityaudit.config', 'setRevisionTypeFieldName', ['%simplethings.entityaudit.revision_type_field_name%']);
$this->assertContainerBuilderHasServiceDefinitionWithMethodCall('simplethings_entityaudit.config', 'setDisabledForeignKeys', ['%simplethings.entityaudit.disable_foreign_keys%']);
$this->assertContainerBuilderHasServiceDefinitionWithMethodCall('simplethings_entityaudit.config', 'setUsernameCallable', ['simplethings_entityaudit.username_callable']);
}

Expand Down Expand Up @@ -102,6 +103,7 @@ public function testItSetsDefaultParameters(): void
$this->assertContainerBuilderHasParameter('simplethings.entityaudit.revision_field_name', 'rev');
$this->assertContainerBuilderHasParameter('simplethings.entityaudit.revision_type_field_name', 'revtype');
$this->assertContainerBuilderHasParameter('simplethings.entityaudit.revision_id_field_type', Types::INTEGER);
$this->assertContainerBuilderHasParameter('simplethings.entityaudit.disable_foreign_keys', false);
}

public function testItSetsConfiguredParameters(): void
Expand All @@ -117,6 +119,7 @@ public function testItSetsConfiguredParameters(): void
'revision_id_field_type' => Types::GUID,
'revision_field_name' => 'revision',
'revision_type_field_name' => 'action',
'disable_foreign_keys' => false,
]);

$this->assertContainerBuilderHasParameter('simplethings.entityaudit.connection', 'my_custom_connection');
Expand All @@ -129,6 +132,7 @@ public function testItSetsConfiguredParameters(): void
$this->assertContainerBuilderHasParameter('simplethings.entityaudit.revision_id_field_type', Types::GUID);
$this->assertContainerBuilderHasParameter('simplethings.entityaudit.revision_field_name', 'revision');
$this->assertContainerBuilderHasParameter('simplethings.entityaudit.revision_type_field_name', 'action');
$this->assertContainerBuilderHasParameter('simplethings.entityaudit.disable_foreign_keys', false);

foreach ([Events::onFlush, Events::postPersist, Events::postUpdate, Events::postFlush, Events::onClear] as $event) {
$this->assertContainerBuilderHasServiceDefinitionWithTag('simplethings_entityaudit.log_revisions_listener', 'doctrine.event_listener', ['event' => $event, 'connection' => 'my_custom_connection']);
Expand Down
82 changes: 82 additions & 0 deletions tests/NoForeignKeysTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
<?php

declare(strict_types=1);

/*
* This file is part of the Sonata Project package.
*
* (c) Thomas Rabaix <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Sonata\EntityAuditBundle\Tests;

use Doctrine\DBAL\Exception;
use Doctrine\ORM\Exception\ORMException;
use Doctrine\ORM\OptimisticLockException;
use SimpleThings\EntityAudit\AuditConfiguration;
use SimpleThings\EntityAudit\AuditManager;
use SimpleThings\EntityAudit\Exception\NotAuditedException;
use Sonata\EntityAuditBundle\Tests\Fixtures\Core\UserAudit;

final class NoForeignKeysTest extends BaseTest
{
protected $schemaEntities = [
UserAudit::class,
];

protected $auditedEntities = [
UserAudit::class,
];

/**
* @throws OptimisticLockException
* @throws ORMException
* @throws NotAuditedException
* @throws Exception
*/
public function testRevisionForeignKeys(): void
{
$em = $this->getEntityManager();

$user = new UserAudit('phansys');

$em->persist($user);
$em->flush();

$reader = $this->getAuditManager()->createAuditReader($em);

$userId = $user->getId();
static::assertNotNull($userId);

$revisions = $reader->findRevisions(UserAudit::class, $userId);

static::assertCount(1, $revisions);

$revision = $reader->getCurrentRevision(UserAudit::class, $userId);
static::assertSame('1', (string) $revision);

$revisionsTableName = $this->getAuditManager()->getConfiguration()->getRevisionTableName();

$em->getConnection()->delete($revisionsTableName, ['id' => $revision]);
}

protected function getAuditManager(): AuditManager
{
if (null !== $this->auditManager) {
return $this->auditManager;
}

$auditConfig = AuditConfiguration::forEntities($this->auditedEntities);
$auditConfig->setGlobalIgnoreColumns(['ignoreme']);
$auditConfig->setDisabledForeignKeys(true);
$auditConfig->setUsernameCallable(static fn (): string => 'beberlei');

$this->auditManager = new AuditManager($auditConfig, $this->getClock());
$this->auditManager->registerEvents($this->getEntityManager()->getEventManager());

return $this->auditManager;
}
}