|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Rokde\CloneDatabase\Actions; |
| 4 | + |
| 5 | +use Illuminate\Database\ConnectionResolverInterface; |
| 6 | +use Rokde\CloneDatabase\Models\DatabaseSyncConfiguration; |
| 7 | + |
| 8 | +readonly class Synchronize |
| 9 | +{ |
| 10 | + public function __construct( |
| 11 | + protected ConnectionResolverInterface $connections, |
| 12 | + protected DatabaseSyncConfiguration $config |
| 13 | + ) { |
| 14 | + |
| 15 | + } |
| 16 | + |
| 17 | + public function __invoke(): void |
| 18 | + { |
| 19 | + /** @var \Illuminate\Database\Connection|\Illuminate\Database\ConnectionInterface $sourceConnection */ |
| 20 | + $sourceConnection = $this->connections->connectUsing( |
| 21 | + $this->config->sourceConnectionName(), |
| 22 | + $this->config->sourceConnectionConfig(), |
| 23 | + true, |
| 24 | + ); |
| 25 | + |
| 26 | + /** @var \Illuminate\Database\Connection|\Illuminate\Database\ConnectionInterface $targetConnection */ |
| 27 | + $targetConnection = $this->connections->connectUsing( |
| 28 | + $this->config->targetConnectionName(), |
| 29 | + $this->config->targetConnectionConfig(), |
| 30 | + true, |
| 31 | + ); |
| 32 | + |
| 33 | + // start process |
| 34 | + try { |
| 35 | + $targetConnection->getSchemaBuilder()->disableForeignKeyConstraints(); |
| 36 | + |
| 37 | + // structure |
| 38 | + (new SynchronizeStructure( |
| 39 | + dropExistingTables: $this->config->shouldDropTables(), |
| 40 | + keepUnhandledTablesOnTarget: $this->config->shouldKeepUnhandledTablesOnTarget()) |
| 41 | + )($sourceConnection, $targetConnection); |
| 42 | + |
| 43 | + $sourceSchema = $sourceConnection->getDoctrineSchemaManager(); |
| 44 | + // copy data |
| 45 | + collect($sourceSchema->listTableNames()) |
| 46 | + ->each(function (string $tableName) use ($sourceSchema) { |
| 47 | + |
| 48 | + (new SynchronizeTable( |
| 49 | + table: $tableName, |
| 50 | + sourceConnectionName: $this->config->sourceConnectionName(), |
| 51 | + targetConnectionName: $this->config->targetConnectionName(), |
| 52 | + deleteRecords: $this->config->shouldDeleteRecords(), |
| 53 | + ))( |
| 54 | + mutations: $this->config->mutationsFor($tableName), |
| 55 | + chunks: $this->config->chunksFor($tableName), |
| 56 | + limit: $this->config->limitFor($tableName), |
| 57 | + sourceSchema: $sourceSchema, |
| 58 | + ); |
| 59 | + |
| 60 | + }); |
| 61 | + |
| 62 | + $targetConnection->getSchemaBuilder()->enableForeignKeyConstraints(); |
| 63 | + |
| 64 | + $targetSchema = $targetConnection->getDoctrineSchemaManager(); |
| 65 | + // views |
| 66 | + (new SynchronizeViews())($sourceSchema, $targetSchema); |
| 67 | + } catch (\Exception $exception) { |
| 68 | + $targetConnection->getSchemaBuilder()->enableForeignKeyConstraints(); |
| 69 | + } |
| 70 | + } |
| 71 | +} |
0 commit comments