|
4 | 4 |
|
5 | 5 | namespace OCA\Cookbook\Migration; |
6 | 6 |
|
7 | | -use Closure; |
| 7 | +use OCP\IDBConnection; |
8 | 8 | use OCP\DB\ISchemaWrapper; |
9 | 9 | use OCP\Migration\IOutput; |
10 | 10 | use OCP\Migration\SimpleMigrationStep; |
| 11 | +use Closure; |
| 12 | +use OCP\DB\QueryBuilder\IQueryBuilder; |
11 | 13 |
|
12 | 14 | /** |
13 | 15 | * Auto-generated migration step: Please modify to your needs! |
14 | 16 | */ |
15 | 17 | class Version000000Date20210701093123 extends SimpleMigrationStep { |
16 | 18 |
|
| 19 | + /** |
| 20 | + * @var IDBConnection |
| 21 | + */ |
| 22 | + private $db; |
| 23 | + |
| 24 | + public function __construct(IDBConnection $db) { |
| 25 | + $this->db = $db; |
| 26 | + } |
| 27 | + |
| 28 | + public function preSchemaChange(IOutput $output, \Closure $schemaClosure, array $options) { |
| 29 | + $this->db->beginTransaction(); |
| 30 | + try { |
| 31 | + $qb = $this->db->getQueryBuilder(); |
| 32 | + |
| 33 | + // Fetch all rows that are non-unique |
| 34 | + $qb->selectAlias('n.user_id', 'user') |
| 35 | + ->selectAlias('n.recipe_id', 'recipe') |
| 36 | + ->from('cookbook_names', 'n') |
| 37 | + ->groupBy('n.user_id', 'n.recipe_id') |
| 38 | + ->having('COUNT(*) > 1'); |
| 39 | + //echo $qb->getSQL() . "\n"; |
| 40 | + |
| 41 | + $cursor = $qb->execute(); |
| 42 | + $result = $cursor->fetchAll(); |
| 43 | + |
| 44 | + if (sizeof($result) > 0) { |
| 45 | + // We have to fix the database |
| 46 | + |
| 47 | + // Drop all redundant rows |
| 48 | + $qb = $this->db->getQueryBuilder(); |
| 49 | + $qb->delete('cookbook_names') |
| 50 | + ->where( |
| 51 | + 'user_id = :user', |
| 52 | + 'recipe_id = :recipe' |
| 53 | + ); |
| 54 | + |
| 55 | + $qb2 = $this->db->getQueryBuilder(); |
| 56 | + $qb2->update('preferences') |
| 57 | + ->set('configvalue', $qb->expr()->literal('1', IQueryBuilder::PARAM_STR)) |
| 58 | + ->where( |
| 59 | + 'userid = :user', |
| 60 | + 'appid = :app', |
| 61 | + 'configkey = :property' |
| 62 | + ); |
| 63 | + $qb2->setParameter('app', 'cookbook'); |
| 64 | + $qb2->setParameter('property', 'last_index_update'); |
| 65 | + |
| 66 | + foreach ($result as $r) { |
| 67 | + $qb->setParameter('user', $r['user']); |
| 68 | + $qb->setParameter('recipe', $r['recipe']); |
| 69 | + $qb->execute(); |
| 70 | + |
| 71 | + $qb2->setParameter('user', $r['user']); |
| 72 | + $qb2->execute(); |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + // Finish the transaction |
| 77 | + $this->db->commit(); |
| 78 | + } catch (\Exception $e) { |
| 79 | + // Abort the transaction |
| 80 | + $this->db->rollBack(); |
| 81 | + throw $e; |
| 82 | + } |
| 83 | + } |
| 84 | + |
17 | 85 | /** |
18 | 86 | * @param IOutput $output |
19 | 87 | * @param Closure $schemaClosure The `\Closure` returns a `ISchemaWrapper` |
|
0 commit comments