Completed
Push — master ( 47b2ba...97e8f3 )
by Thomas
27s
created

Migrator::dropTable()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * @author martin-rueegg <[email protected]>
4
 * @author Morris Jobke <[email protected]>
5
 * @author Robin Appelman <[email protected]>
6
 * @author tbelau666 <[email protected]>
7
 * @author Thomas Müller <[email protected]>
8
 * @author Victor Dubiniuk <[email protected]>
9
 * @author Vincent Petry <[email protected]>
10
 *
11
 * @copyright Copyright (c) 2016, ownCloud GmbH.
12
 * @license AGPL-3.0
13
 *
14
 * This code is free software: you can redistribute it and/or modify
15
 * it under the terms of the GNU Affero General Public License, version 3,
16
 * as published by the Free Software Foundation.
17
 *
18
 * This program is distributed in the hope that it will be useful,
19
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21
 * GNU Affero General Public License for more details.
22
 *
23
 * You should have received a copy of the GNU Affero General Public License, version 3,
24
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
25
 *
26
 */
27
28
namespace OC\DB;
29
30
use \Doctrine\DBAL\DBALException;
31
use \Doctrine\DBAL\Schema\Index;
32
use \Doctrine\DBAL\Schema\Table;
33
use \Doctrine\DBAL\Schema\Schema;
34
use \Doctrine\DBAL\Schema\SchemaConfig;
35
use \Doctrine\DBAL\Schema\Comparator;
36
use Doctrine\DBAL\Types\StringType;
37
use Doctrine\DBAL\Types\Type;
38
use OCP\IConfig;
39
use OCP\Security\ISecureRandom;
40
use Symfony\Component\EventDispatcher\EventDispatcher;
41
use Symfony\Component\EventDispatcher\GenericEvent;
42
43
class Migrator {
44
45
	/** @var \Doctrine\DBAL\Connection $connection */
46
	protected $connection;
47
48
	/** @var ISecureRandom */
49
	private $random;
50
51
	/** @var IConfig */
52
	protected $config;
53
54
	/** @var EventDispatcher  */
55
	private $dispatcher;
56
57
	/** @var bool */
58
	private $noEmit = false;
59
60
	/**
61
	 * @param \Doctrine\DBAL\Connection|Connection $connection
62
	 * @param ISecureRandom $random
63
	 * @param IConfig $config
64
	 * @param EventDispatcher $dispatcher
65
	 */
66
	public function __construct(\Doctrine\DBAL\Connection $connection,
67
								ISecureRandom $random,
68
								IConfig $config,
69
								EventDispatcher $dispatcher = null) {
70
		$this->connection = $connection;
71
		$this->random = $random;
72
		$this->config = $config;
73
		$this->dispatcher = $dispatcher;
74
	}
75
76
	/**
77
	 * @param \Doctrine\DBAL\Schema\Schema $targetSchema
78
	 */
79
	public function migrate(Schema $targetSchema) {
80
		$this->noEmit = true;
81
		$this->applySchema($targetSchema);
82
	}
83
84
	/**
85
	 * @param \Doctrine\DBAL\Schema\Schema $targetSchema
86
	 * @return string
87
	 */
88
	public function generateChangeScript(Schema $targetSchema) {
89
		$schemaDiff = $this->getDiff($targetSchema, $this->connection);
90
91
		$script = '';
92
		$sqls = $schemaDiff->toSql($this->connection->getDatabasePlatform());
93
		foreach ($sqls as $sql) {
94
			$script .= $this->convertStatementToScript($sql);
95
		}
96
97
		return $script;
98
	}
99
100
	/**
101
	 * @param Schema $targetSchema
102
	 * @throws \OC\DB\MigrationException
103
	 */
104
	public function checkMigrate(Schema $targetSchema) {
105
		$this->noEmit = true;
106
		/**@var \Doctrine\DBAL\Schema\Table[] $tables */
107
		$tables = $targetSchema->getTables();
108
		$filterExpression = $this->getFilterExpression();
109
		$this->connection->getConfiguration()->
110
			setFilterSchemaAssetsExpression($filterExpression);
111
		$existingTables = $this->connection->getSchemaManager()->listTableNames();
112
113
		$step = 0;
114
		foreach ($tables as $table) {
115
			if (strpos($table->getName(), '.')) {
116
				list(, $tableName) = explode('.', $table->getName());
117
			} else {
118
				$tableName = $table->getName();
119
			}
120
			$this->emitCheckStep($tableName, $step++, count($tables));
121
			// don't need to check for new tables
122
			if (array_search($tableName, $existingTables) !== false) {
123
				$this->checkTableMigrate($table);
124
			}
125
		}
126
	}
127
128
	/**
129
	 * Create a unique name for the temporary table
130
	 *
131
	 * @param string $name
132
	 * @return string
133
	 */
134
	protected function generateTemporaryTableName($name) {
135
		return $this->config->getSystemValue('dbtableprefix', 'oc_') . $name . '_' . $this->random->generate(13, ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS);
136
	}
137
138
	/**
139
	 * Check the migration of a table on a copy so we can detect errors before messing with the real table
140
	 *
141
	 * @param \Doctrine\DBAL\Schema\Table $table
142
	 * @throws \OC\DB\MigrationException
143
	 */
144
	protected function checkTableMigrate(Table $table) {
145
		$name = $table->getName();
146
		$tmpName = $this->generateTemporaryTableName($name);
147
148
		$this->copyTable($name, $tmpName);
149
150
		//create the migration schema for the temporary table
151
		$tmpTable = $this->renameTableSchema($table, $tmpName);
152
		$schemaConfig = new SchemaConfig();
153
		$schemaConfig->setName($this->connection->getDatabase());
154
		$schema = new Schema([$tmpTable], [], $schemaConfig);
155
156
		try {
157
			$this->applySchema($schema);
158
			$this->dropTable($tmpName);
159
		} catch (DBALException $e) {
160
			// pgsql needs to commit it's failed transaction before doing anything else
161
			if ($this->connection->isTransactionActive()) {
162
				$this->connection->commit();
163
			}
164
			$this->dropTable($tmpName);
165
			throw new MigrationException($table->getName(), $e->getMessage());
166
		}
167
	}
168
169
	/**
170
	 * @param \Doctrine\DBAL\Schema\Table $table
171
	 * @param string $newName
172
	 * @return \Doctrine\DBAL\Schema\Table
173
	 */
174
	protected function renameTableSchema(Table $table, $newName) {
175
		/**
176
		 * @var \Doctrine\DBAL\Schema\Index[] $indexes
177
		 */
178
		$indexes = $table->getIndexes();
179
		$newIndexes = [];
180
		foreach ($indexes as $index) {
181
			if ($index->isPrimary()) {
182
				// do not rename primary key
183
				$indexName = $index->getName();
184
			} else {
185
				// avoid conflicts in index names
186
				$indexName = $this->config->getSystemValue('dbtableprefix', 'oc_') . $this->random->generate(13, ISecureRandom::CHAR_LOWER);
187
			}
188
			$newIndexes[] = new Index($indexName, $index->getColumns(), $index->isUnique(), $index->isPrimary());
189
		}
190
191
		// foreign keys are not supported so we just set it to an empty array
192
		return new Table($newName, $table->getColumns(), $newIndexes, [], 0, $table->getOptions());
193
	}
194
195
	public function createSchema() {
196
		$filterExpression = $this->getFilterExpression();
197
		$this->connection->getConfiguration()->setFilterSchemaAssetsExpression($filterExpression);
198
		return $this->connection->getSchemaManager()->createSchema();
199
	}
200
201
	/**
202
	 * @param Schema $targetSchema
203
	 * @param \Doctrine\DBAL\Connection $connection
204
	 * @return \Doctrine\DBAL\Schema\SchemaDiff
205
	 * @throws DBALException
206
	 */
207
	protected function getDiff(Schema $targetSchema, \Doctrine\DBAL\Connection $connection) {
208
		// adjust varchar columns with a length higher then getVarcharMaxLength to clob
209
		foreach ($targetSchema->getTables() as $table) {
210
			foreach ($table->getColumns() as $column) {
211
				if ($column->getType() instanceof StringType) {
212
					if ($column->getLength() > $connection->getDatabasePlatform()->getVarcharMaxLength()) {
213
						$column->setType(Type::getType('text'));
214
						$column->setLength(null);
215
					}
216
				}
217
			}
218
		}
219
220
		$filterExpression = $this->getFilterExpression();
221
		$this->connection->getConfiguration()->setFilterSchemaAssetsExpression($filterExpression);
222
		$sourceSchema = $connection->getSchemaManager()->createSchema();
223
224
		// remove tables we don't know about
225
		/** @var $table \Doctrine\DBAL\Schema\Table */
226
		foreach ($sourceSchema->getTables() as $table) {
227
			if (!$targetSchema->hasTable($table->getName())) {
228
				$sourceSchema->dropTable($table->getName());
229
			}
230
		}
231
		// remove sequences we don't know about
232
		foreach ($sourceSchema->getSequences() as $table) {
233
			if (!$targetSchema->hasSequence($table->getName())) {
234
				$sourceSchema->dropSequence($table->getName());
235
			}
236
		}
237
238
		$comparator = new Comparator();
239
		return $comparator->compare($sourceSchema, $targetSchema);
240
	}
241
242
	/**
243
	 * @param \Doctrine\DBAL\Schema\Schema $targetSchema
244
	 * @param \Doctrine\DBAL\Connection $connection
245
	 */
246
	protected function applySchema(Schema $targetSchema, \Doctrine\DBAL\Connection $connection = null) {
247
		if (is_null($connection)) {
248
			$connection = $this->connection;
249
		}
250
251
		$schemaDiff = $this->getDiff($targetSchema, $connection);
252
253
		$connection->beginTransaction();
254
		$sqls = $schemaDiff->toSql($connection->getDatabasePlatform());
255
		$step = 0;
256
		foreach ($sqls as $sql) {
257
			$this->emit($sql, $step++, count($sqls));
258
			$connection->query($sql);
259
		}
260
		$connection->commit();
261
	}
262
263
	/**
264
	 * @param string $sourceName
265
	 * @param string $targetName
266
	 */
267
	protected function copyTable($sourceName, $targetName) {
268
		$quotedSource = $this->connection->quoteIdentifier($sourceName);
269
		$quotedTarget = $this->connection->quoteIdentifier($targetName);
270
271
		$this->connection->exec('CREATE TABLE ' . $quotedTarget . ' (LIKE ' . $quotedSource . ')');
272
		$this->connection->exec('INSERT INTO ' . $quotedTarget . ' SELECT * FROM ' . $quotedSource);
273
	}
274
275
	/**
276
	 * @param string $name
277
	 */
278
	protected function dropTable($name) {
279
		$this->connection->exec('DROP TABLE ' . $this->connection->quoteIdentifier($name));
280
	}
281
282
	/**
283
	 * @param $statement
284
	 * @return string
285
	 */
286
	protected function convertStatementToScript($statement) {
287
		$script = $statement . ';';
288
		$script .= PHP_EOL;
289
		$script .= PHP_EOL;
290
		return $script;
291
	}
292
293
	protected function getFilterExpression() {
294
		return '/^' . preg_quote($this->config->getSystemValue('dbtableprefix', 'oc_')) . '/';
295
	}
296
297
	protected function emit($sql, $step, $max) {
298
		if ($this->noEmit) {
299
			return;
300
		}
301
		if(is_null($this->dispatcher)) {
302
			return;
303
		}
304
		$this->dispatcher->dispatch('\OC\DB\Migrator::executeSql', new GenericEvent($sql, [$step+1, $max]));
305
	}
306
307
	private function emitCheckStep($tableName, $step, $max) {
308
		if(is_null($this->dispatcher)) {
309
			return;
310
		}
311
		$this->dispatcher->dispatch('\OC\DB\Migrator::checkTable', new GenericEvent($tableName, [$step+1, $max]));
312
	}
313
}
314