Passed
Push — master ( 410e29...0c7bed )
by Morris
32:13 queued 21:01
created
lib/private/DB/MySQLMigrator.php 1 patch
Indentation   +38 added lines, -38 removed lines patch added patch discarded remove patch
@@ -29,47 +29,47 @@
 block discarded – undo
29 29
 use Doctrine\DBAL\Schema\Table;
30 30
 
31 31
 class MySQLMigrator extends Migrator {
32
-	/**
33
-	 * @param Schema $targetSchema
34
-	 * @param \Doctrine\DBAL\Connection $connection
35
-	 * @return \Doctrine\DBAL\Schema\SchemaDiff
36
-	 */
37
-	protected function getDiff(Schema $targetSchema, \Doctrine\DBAL\Connection $connection) {
38
-		$platform = $connection->getDatabasePlatform();
39
-		$platform->registerDoctrineTypeMapping('enum', 'string');
40
-		$platform->registerDoctrineTypeMapping('bit', 'string');
32
+    /**
33
+     * @param Schema $targetSchema
34
+     * @param \Doctrine\DBAL\Connection $connection
35
+     * @return \Doctrine\DBAL\Schema\SchemaDiff
36
+     */
37
+    protected function getDiff(Schema $targetSchema, \Doctrine\DBAL\Connection $connection) {
38
+        $platform = $connection->getDatabasePlatform();
39
+        $platform->registerDoctrineTypeMapping('enum', 'string');
40
+        $platform->registerDoctrineTypeMapping('bit', 'string');
41 41
 
42
-		$schemaDiff = parent::getDiff($targetSchema, $connection);
42
+        $schemaDiff = parent::getDiff($targetSchema, $connection);
43 43
 
44
-		// identifiers need to be quoted for mysql
45
-		foreach ($schemaDiff->changedTables as $tableDiff) {
46
-			$tableDiff->name = $this->connection->quoteIdentifier($tableDiff->name);
47
-			foreach ($tableDiff->changedColumns as $column) {
48
-				$column->oldColumnName = $this->connection->quoteIdentifier($column->oldColumnName);
49
-			}
50
-		}
44
+        // identifiers need to be quoted for mysql
45
+        foreach ($schemaDiff->changedTables as $tableDiff) {
46
+            $tableDiff->name = $this->connection->quoteIdentifier($tableDiff->name);
47
+            foreach ($tableDiff->changedColumns as $column) {
48
+                $column->oldColumnName = $this->connection->quoteIdentifier($column->oldColumnName);
49
+            }
50
+        }
51 51
 
52
-		return $schemaDiff;
53
-	}
52
+        return $schemaDiff;
53
+    }
54 54
 	
55
-	/**
56
-	 * Speed up migration test by disabling autocommit and unique indexes check
57
-	 *
58
-	 * @param \Doctrine\DBAL\Schema\Table $table
59
-	 * @throws \OC\DB\MigrationException
60
-	 */
61
-	protected function checkTableMigrate(Table $table) {
62
-		$this->connection->exec('SET autocommit=0');
63
-		$this->connection->exec('SET unique_checks=0');
55
+    /**
56
+     * Speed up migration test by disabling autocommit and unique indexes check
57
+     *
58
+     * @param \Doctrine\DBAL\Schema\Table $table
59
+     * @throws \OC\DB\MigrationException
60
+     */
61
+    protected function checkTableMigrate(Table $table) {
62
+        $this->connection->exec('SET autocommit=0');
63
+        $this->connection->exec('SET unique_checks=0');
64 64
 
65
-		try {
66
-			parent::checkTableMigrate($table);
67
-		} catch (\Exception $e) {
68
-			$this->connection->exec('SET unique_checks=1');
69
-			$this->connection->exec('SET autocommit=1');
70
-			throw new MigrationException($table->getName(), $e->getMessage());
71
-		}
72
-		$this->connection->exec('SET unique_checks=1');
73
-		$this->connection->exec('SET autocommit=1');
74
-	}
65
+        try {
66
+            parent::checkTableMigrate($table);
67
+        } catch (\Exception $e) {
68
+            $this->connection->exec('SET unique_checks=1');
69
+            $this->connection->exec('SET autocommit=1');
70
+            throw new MigrationException($table->getName(), $e->getMessage());
71
+        }
72
+        $this->connection->exec('SET unique_checks=1');
73
+        $this->connection->exec('SET autocommit=1');
74
+    }
75 75
 }
Please login to merge, or discard this patch.
lib/private/DB/PgSqlTools.php 2 patches
Indentation   +32 added lines, -32 removed lines patch added patch discarded remove patch
@@ -32,41 +32,41 @@
 block discarded – undo
32 32
  */
33 33
 class PgSqlTools {
34 34
 
35
-	/** @var \OCP\IConfig */
36
-	private $config;
35
+    /** @var \OCP\IConfig */
36
+    private $config;
37 37
 
38
-	/**
39
-	 * @param \OCP\IConfig $config
40
-	 */
41
-	public function __construct(IConfig $config) {
42
-		$this->config = $config;
43
-	}
38
+    /**
39
+     * @param \OCP\IConfig $config
40
+     */
41
+    public function __construct(IConfig $config) {
42
+        $this->config = $config;
43
+    }
44 44
 
45
-	/**
46
-	 * @brief Resynchronizes all sequences of a database after using INSERTs
47
-	 *        without leaving out the auto-incremented column.
48
-	 * @param \OC\DB\Connection $conn
49
-	 * @return null
50
-	 */
51
-	public function resynchronizeDatabaseSequences(Connection $conn) {
52
-		$filterExpression = '/^' . preg_quote($this->config->getSystemValue('dbtableprefix', 'oc_')) . '/';
53
-		$databaseName = $conn->getDatabase();
54
-		$conn->getConfiguration()->setFilterSchemaAssetsExpression($filterExpression);
45
+    /**
46
+     * @brief Resynchronizes all sequences of a database after using INSERTs
47
+     *        without leaving out the auto-incremented column.
48
+     * @param \OC\DB\Connection $conn
49
+     * @return null
50
+     */
51
+    public function resynchronizeDatabaseSequences(Connection $conn) {
52
+        $filterExpression = '/^' . preg_quote($this->config->getSystemValue('dbtableprefix', 'oc_')) . '/';
53
+        $databaseName = $conn->getDatabase();
54
+        $conn->getConfiguration()->setFilterSchemaAssetsExpression($filterExpression);
55 55
 
56
-		foreach ($conn->getSchemaManager()->listSequences() as $sequence) {
57
-			$sequenceName = $sequence->getName();
58
-			$sqlInfo = 'SELECT table_schema, table_name, column_name
56
+        foreach ($conn->getSchemaManager()->listSequences() as $sequence) {
57
+            $sequenceName = $sequence->getName();
58
+            $sqlInfo = 'SELECT table_schema, table_name, column_name
59 59
 				FROM information_schema.columns
60 60
 				WHERE column_default = ? AND table_catalog = ?';
61
-			$sequenceInfo = $conn->fetchAssoc($sqlInfo, [
62
-				"nextval('$sequenceName'::regclass)",
63
-				$databaseName
64
-			]);
65
-			$tableName = $sequenceInfo['table_name'];
66
-			$columnName = $sequenceInfo['column_name'];
67
-			$sqlMaxId = "SELECT MAX($columnName) FROM $tableName";
68
-			$sqlSetval = "SELECT setval('$sequenceName', ($sqlMaxId))";
69
-			$conn->executeQuery($sqlSetval);
70
-		}
71
-	}
61
+            $sequenceInfo = $conn->fetchAssoc($sqlInfo, [
62
+                "nextval('$sequenceName'::regclass)",
63
+                $databaseName
64
+            ]);
65
+            $tableName = $sequenceInfo['table_name'];
66
+            $columnName = $sequenceInfo['column_name'];
67
+            $sqlMaxId = "SELECT MAX($columnName) FROM $tableName";
68
+            $sqlSetval = "SELECT setval('$sequenceName', ($sqlMaxId))";
69
+            $conn->executeQuery($sqlSetval);
70
+        }
71
+    }
72 72
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -49,7 +49,7 @@
 block discarded – undo
49 49
 	 * @return null
50 50
 	 */
51 51
 	public function resynchronizeDatabaseSequences(Connection $conn) {
52
-		$filterExpression = '/^' . preg_quote($this->config->getSystemValue('dbtableprefix', 'oc_')) . '/';
52
+		$filterExpression = '/^'.preg_quote($this->config->getSystemValue('dbtableprefix', 'oc_')).'/';
53 53
 		$databaseName = $conn->getDatabase();
54 54
 		$conn->getConfiguration()->setFilterSchemaAssetsExpression($filterExpression);
55 55
 
Please login to merge, or discard this patch.
lib/private/DB/AdapterSqlite.php 2 patches
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -64,14 +64,14 @@
 block discarded – undo
64 64
 		if (empty($compare)) {
65 65
 			$compare = array_keys($input);
66 66
 		}
67
-		$fieldList = '`' . implode('`,`', array_keys($input)) . '`';
67
+		$fieldList = '`'.implode('`,`', array_keys($input)).'`';
68 68
 		$query = "INSERT INTO `$table` ($fieldList) SELECT "
69 69
 			. str_repeat('?,', count($input) - 1).'? '
70 70
 			. " WHERE NOT EXISTS (SELECT 1 FROM `$table` WHERE ";
71 71
 
72 72
 		$inserts = array_values($input);
73 73
 		foreach ($compare as $key) {
74
-			$query .= '`' . $key . '`';
74
+			$query .= '`'.$key.'`';
75 75
 			if (is_null($input[$key])) {
76 76
 				$query .= ' IS NULL AND ';
77 77
 			} else {
Please login to merge, or discard this patch.
Indentation   +61 added lines, -61 removed lines patch added patch discarded remove patch
@@ -31,70 +31,70 @@
 block discarded – undo
31 31
 
32 32
 class AdapterSqlite extends Adapter {
33 33
 
34
-	/**
35
-	 * @param string $tableName
36
-	 */
37
-	public function lockTable($tableName) {
38
-		$this->conn->executeUpdate('BEGIN EXCLUSIVE TRANSACTION');
39
-	}
34
+    /**
35
+     * @param string $tableName
36
+     */
37
+    public function lockTable($tableName) {
38
+        $this->conn->executeUpdate('BEGIN EXCLUSIVE TRANSACTION');
39
+    }
40 40
 
41
-	public function unlockTable() {
42
-		$this->conn->executeUpdate('COMMIT TRANSACTION');
43
-	}
41
+    public function unlockTable() {
42
+        $this->conn->executeUpdate('COMMIT TRANSACTION');
43
+    }
44 44
 
45
-	public function fixupStatement($statement) {
46
-		$statement = preg_replace('/`(\w+)` ILIKE \?/', 'LOWER($1) LIKE LOWER(?)', $statement);
47
-		$statement = str_replace('`', '"', $statement);
48
-		$statement = str_ireplace('NOW()', 'datetime(\'now\')', $statement);
49
-		$statement = str_ireplace('GREATEST(', 'MAX(', $statement);
50
-		$statement = str_ireplace('UNIX_TIMESTAMP()', 'strftime(\'%s\',\'now\')', $statement);
51
-		return $statement;
52
-	}
45
+    public function fixupStatement($statement) {
46
+        $statement = preg_replace('/`(\w+)` ILIKE \?/', 'LOWER($1) LIKE LOWER(?)', $statement);
47
+        $statement = str_replace('`', '"', $statement);
48
+        $statement = str_ireplace('NOW()', 'datetime(\'now\')', $statement);
49
+        $statement = str_ireplace('GREATEST(', 'MAX(', $statement);
50
+        $statement = str_ireplace('UNIX_TIMESTAMP()', 'strftime(\'%s\',\'now\')', $statement);
51
+        return $statement;
52
+    }
53 53
 
54
-	/**
55
-	 * Insert a row if the matching row does not exists. To accomplish proper race condition avoidance
56
-	 * it is needed that there is also a unique constraint on the values. Then this method will
57
-	 * catch the exception and return 0.
58
-	 *
59
-	 * @param string $table The table name (will replace *PREFIX* with the actual prefix)
60
-	 * @param array $input data that should be inserted into the table  (column name => value)
61
-	 * @param array|null $compare List of values that should be checked for "if not exists"
62
-	 *				If this is null or an empty array, all keys of $input will be compared
63
-	 *				Please note: text fields (clob) must not be used in the compare array
64
-	 * @return int number of inserted rows
65
-	 * @throws \Doctrine\DBAL\DBALException
66
-	 * @deprecated 15.0.0 - use unique index and "try { $db->insert() } catch (UniqueConstraintViolationException $e) {}" instead, because it is more reliable and does not have the risk for deadlocks - see https://github.com/nextcloud/server/pull/12371
67
-	 */
68
-	public function insertIfNotExist($table, $input, array $compare = null) {
69
-		if (empty($compare)) {
70
-			$compare = array_keys($input);
71
-		}
72
-		$fieldList = '`' . implode('`,`', array_keys($input)) . '`';
73
-		$query = "INSERT INTO `$table` ($fieldList) SELECT "
74
-			. str_repeat('?,', count($input) - 1).'? '
75
-			. " WHERE NOT EXISTS (SELECT 1 FROM `$table` WHERE ";
54
+    /**
55
+     * Insert a row if the matching row does not exists. To accomplish proper race condition avoidance
56
+     * it is needed that there is also a unique constraint on the values. Then this method will
57
+     * catch the exception and return 0.
58
+     *
59
+     * @param string $table The table name (will replace *PREFIX* with the actual prefix)
60
+     * @param array $input data that should be inserted into the table  (column name => value)
61
+     * @param array|null $compare List of values that should be checked for "if not exists"
62
+     *				If this is null or an empty array, all keys of $input will be compared
63
+     *				Please note: text fields (clob) must not be used in the compare array
64
+     * @return int number of inserted rows
65
+     * @throws \Doctrine\DBAL\DBALException
66
+     * @deprecated 15.0.0 - use unique index and "try { $db->insert() } catch (UniqueConstraintViolationException $e) {}" instead, because it is more reliable and does not have the risk for deadlocks - see https://github.com/nextcloud/server/pull/12371
67
+     */
68
+    public function insertIfNotExist($table, $input, array $compare = null) {
69
+        if (empty($compare)) {
70
+            $compare = array_keys($input);
71
+        }
72
+        $fieldList = '`' . implode('`,`', array_keys($input)) . '`';
73
+        $query = "INSERT INTO `$table` ($fieldList) SELECT "
74
+            . str_repeat('?,', count($input) - 1).'? '
75
+            . " WHERE NOT EXISTS (SELECT 1 FROM `$table` WHERE ";
76 76
 
77
-		$inserts = array_values($input);
78
-		foreach ($compare as $key) {
79
-			$query .= '`' . $key . '`';
80
-			if (is_null($input[$key])) {
81
-				$query .= ' IS NULL AND ';
82
-			} else {
83
-				$inserts[] = $input[$key];
84
-				$query .= ' = ? AND ';
85
-			}
86
-		}
87
-		$query = substr($query, 0, -5);
88
-		$query .= ')';
77
+        $inserts = array_values($input);
78
+        foreach ($compare as $key) {
79
+            $query .= '`' . $key . '`';
80
+            if (is_null($input[$key])) {
81
+                $query .= ' IS NULL AND ';
82
+            } else {
83
+                $inserts[] = $input[$key];
84
+                $query .= ' = ? AND ';
85
+            }
86
+        }
87
+        $query = substr($query, 0, -5);
88
+        $query .= ')';
89 89
 
90
-		try {
91
-			return $this->conn->executeUpdate($query, $inserts);
92
-		} catch (UniqueConstraintViolationException $e) {
93
-			// if this is thrown then a concurrent insert happened between the insert and the sub-select in the insert, that should have avoided it
94
-			// it's fine to ignore this then
95
-			//
96
-			// more discussions about this can be found at https://github.com/nextcloud/server/pull/12315
97
-			return 0;
98
-		}
99
-	}
90
+        try {
91
+            return $this->conn->executeUpdate($query, $inserts);
92
+        } catch (UniqueConstraintViolationException $e) {
93
+            // if this is thrown then a concurrent insert happened between the insert and the sub-select in the insert, that should have avoided it
94
+            // it's fine to ignore this then
95
+            //
96
+            // more discussions about this can be found at https://github.com/nextcloud/server/pull/12315
97
+            return 0;
98
+        }
99
+    }
100 100
 }
Please login to merge, or discard this patch.
lib/private/DB/MDB2SchemaReader.php 2 patches
Indentation   +292 added lines, -292 removed lines patch added patch discarded remove patch
@@ -37,312 +37,312 @@
 block discarded – undo
37 37
 
38 38
 class MDB2SchemaReader {
39 39
 
40
-	/**
41
-	 * @var string $DBTABLEPREFIX
42
-	 */
43
-	protected $DBTABLEPREFIX;
40
+    /**
41
+     * @var string $DBTABLEPREFIX
42
+     */
43
+    protected $DBTABLEPREFIX;
44 44
 
45
-	/**
46
-	 * @var \Doctrine\DBAL\Platforms\AbstractPlatform $platform
47
-	 */
48
-	protected $platform;
45
+    /**
46
+     * @var \Doctrine\DBAL\Platforms\AbstractPlatform $platform
47
+     */
48
+    protected $platform;
49 49
 
50
-	/** @var IConfig */
51
-	protected $config;
50
+    /** @var IConfig */
51
+    protected $config;
52 52
 
53
-	/**
54
-	 * @param \OCP\IConfig $config
55
-	 * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform
56
-	 */
57
-	public function __construct(IConfig $config, AbstractPlatform $platform) {
58
-		$this->platform = $platform;
59
-		$this->config = $config;
60
-		$this->DBTABLEPREFIX = $config->getSystemValue('dbtableprefix', 'oc_');
61
-	}
53
+    /**
54
+     * @param \OCP\IConfig $config
55
+     * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform
56
+     */
57
+    public function __construct(IConfig $config, AbstractPlatform $platform) {
58
+        $this->platform = $platform;
59
+        $this->config = $config;
60
+        $this->DBTABLEPREFIX = $config->getSystemValue('dbtableprefix', 'oc_');
61
+    }
62 62
 
63
-	/**
64
-	 * @param string $file
65
-	 * @param Schema $schema
66
-	 * @return Schema
67
-	 * @throws \DomainException
68
-	 */
69
-	public function loadSchemaFromFile($file, Schema $schema) {
70
-		$loadEntities = libxml_disable_entity_loader(false);
71
-		$xml = simplexml_load_file($file);
72
-		libxml_disable_entity_loader($loadEntities);
73
-		foreach ($xml->children() as $child) {
74
-			/**
75
-			 * @var \SimpleXMLElement $child
76
-			 */
77
-			switch ($child->getName()) {
78
-				case 'name':
79
-				case 'create':
80
-				case 'overwrite':
81
-				case 'charset':
82
-					break;
83
-				case 'table':
84
-					$this->loadTable($schema, $child);
85
-					break;
86
-				default:
87
-					throw new \DomainException('Unknown element: ' . $child->getName());
63
+    /**
64
+     * @param string $file
65
+     * @param Schema $schema
66
+     * @return Schema
67
+     * @throws \DomainException
68
+     */
69
+    public function loadSchemaFromFile($file, Schema $schema) {
70
+        $loadEntities = libxml_disable_entity_loader(false);
71
+        $xml = simplexml_load_file($file);
72
+        libxml_disable_entity_loader($loadEntities);
73
+        foreach ($xml->children() as $child) {
74
+            /**
75
+             * @var \SimpleXMLElement $child
76
+             */
77
+            switch ($child->getName()) {
78
+                case 'name':
79
+                case 'create':
80
+                case 'overwrite':
81
+                case 'charset':
82
+                    break;
83
+                case 'table':
84
+                    $this->loadTable($schema, $child);
85
+                    break;
86
+                default:
87
+                    throw new \DomainException('Unknown element: ' . $child->getName());
88 88
 
89
-			}
90
-		}
91
-		return $schema;
92
-	}
89
+            }
90
+        }
91
+        return $schema;
92
+    }
93 93
 
94
-	/**
95
-	 * @param \Doctrine\DBAL\Schema\Schema $schema
96
-	 * @param \SimpleXMLElement $xml
97
-	 * @throws \DomainException
98
-	 */
99
-	private function loadTable($schema, $xml) {
100
-		$table = null;
101
-		foreach ($xml->children() as $child) {
102
-			/**
103
-			 * @var \SimpleXMLElement $child
104
-			 */
105
-			switch ($child->getName()) {
106
-				case 'name':
107
-					$name = (string)$child;
108
-					$name = str_replace('*dbprefix*', $this->DBTABLEPREFIX, $name);
109
-					$name = $this->platform->quoteIdentifier($name);
110
-					$table = $schema->createTable($name);
111
-					break;
112
-				case 'create':
113
-				case 'overwrite':
114
-				case 'charset':
115
-					break;
116
-				case 'declaration':
117
-					if (is_null($table)) {
118
-						throw new \DomainException('Table declaration before table name');
119
-					}
120
-					$this->loadDeclaration($table, $child);
121
-					break;
122
-				default:
123
-					throw new \DomainException('Unknown element: ' . $child->getName());
94
+    /**
95
+     * @param \Doctrine\DBAL\Schema\Schema $schema
96
+     * @param \SimpleXMLElement $xml
97
+     * @throws \DomainException
98
+     */
99
+    private function loadTable($schema, $xml) {
100
+        $table = null;
101
+        foreach ($xml->children() as $child) {
102
+            /**
103
+             * @var \SimpleXMLElement $child
104
+             */
105
+            switch ($child->getName()) {
106
+                case 'name':
107
+                    $name = (string)$child;
108
+                    $name = str_replace('*dbprefix*', $this->DBTABLEPREFIX, $name);
109
+                    $name = $this->platform->quoteIdentifier($name);
110
+                    $table = $schema->createTable($name);
111
+                    break;
112
+                case 'create':
113
+                case 'overwrite':
114
+                case 'charset':
115
+                    break;
116
+                case 'declaration':
117
+                    if (is_null($table)) {
118
+                        throw new \DomainException('Table declaration before table name');
119
+                    }
120
+                    $this->loadDeclaration($table, $child);
121
+                    break;
122
+                default:
123
+                    throw new \DomainException('Unknown element: ' . $child->getName());
124 124
 
125
-			}
126
-		}
127
-	}
125
+            }
126
+        }
127
+    }
128 128
 
129
-	/**
130
-	 * @param \Doctrine\DBAL\Schema\Table $table
131
-	 * @param \SimpleXMLElement $xml
132
-	 * @throws \DomainException
133
-	 */
134
-	private function loadDeclaration($table, $xml) {
135
-		foreach ($xml->children() as $child) {
136
-			/**
137
-			 * @var \SimpleXMLElement $child
138
-			 */
139
-			switch ($child->getName()) {
140
-				case 'field':
141
-					$this->loadField($table, $child);
142
-					break;
143
-				case 'index':
144
-					$this->loadIndex($table, $child);
145
-					break;
146
-				default:
147
-					throw new \DomainException('Unknown element: ' . $child->getName());
129
+    /**
130
+     * @param \Doctrine\DBAL\Schema\Table $table
131
+     * @param \SimpleXMLElement $xml
132
+     * @throws \DomainException
133
+     */
134
+    private function loadDeclaration($table, $xml) {
135
+        foreach ($xml->children() as $child) {
136
+            /**
137
+             * @var \SimpleXMLElement $child
138
+             */
139
+            switch ($child->getName()) {
140
+                case 'field':
141
+                    $this->loadField($table, $child);
142
+                    break;
143
+                case 'index':
144
+                    $this->loadIndex($table, $child);
145
+                    break;
146
+                default:
147
+                    throw new \DomainException('Unknown element: ' . $child->getName());
148 148
 
149
-			}
150
-		}
151
-	}
149
+            }
150
+        }
151
+    }
152 152
 
153
-	/**
154
-	 * @param \Doctrine\DBAL\Schema\Table $table
155
-	 * @param \SimpleXMLElement $xml
156
-	 * @throws \DomainException
157
-	 */
158
-	private function loadField($table, $xml) {
159
-		$options = [ 'notnull' => false ];
160
-		foreach ($xml->children() as $child) {
161
-			/**
162
-			 * @var \SimpleXMLElement $child
163
-			 */
164
-			switch ($child->getName()) {
165
-				case 'name':
166
-					$name = (string)$child;
167
-					$name = $this->platform->quoteIdentifier($name);
168
-					break;
169
-				case 'type':
170
-					$type = (string)$child;
171
-					switch ($type) {
172
-						case 'text':
173
-							$type = 'string';
174
-							break;
175
-						case 'clob':
176
-							$type = 'text';
177
-							break;
178
-						case 'timestamp':
179
-							$type = 'datetime';
180
-							break;
181
-						case 'numeric':
182
-							$type = 'decimal';
183
-							break;
184
-					}
185
-					break;
186
-				case 'length':
187
-					$length = (string)$child;
188
-					$options['length'] = $length;
189
-					break;
190
-				case 'unsigned':
191
-					$unsigned = $this->asBool($child);
192
-					$options['unsigned'] = $unsigned;
193
-					break;
194
-				case 'notnull':
195
-					$notnull = $this->asBool($child);
196
-					$options['notnull'] = $notnull;
197
-					break;
198
-				case 'autoincrement':
199
-					$autoincrement = $this->asBool($child);
200
-					$options['autoincrement'] = $autoincrement;
201
-					break;
202
-				case 'default':
203
-					$default = (string)$child;
204
-					$options['default'] = $default;
205
-					break;
206
-				case 'comments':
207
-					$comment = (string)$child;
208
-					$options['comment'] = $comment;
209
-					break;
210
-				case 'primary':
211
-					$primary = $this->asBool($child);
212
-					$options['primary'] = $primary;
213
-					break;
214
-				case 'precision':
215
-					$precision = (string)$child;
216
-					$options['precision'] = $precision;
217
-					break;
218
-				case 'scale':
219
-					$scale = (string)$child;
220
-					$options['scale'] = $scale;
221
-					break;
222
-				default:
223
-					throw new \DomainException('Unknown element: ' . $child->getName());
153
+    /**
154
+     * @param \Doctrine\DBAL\Schema\Table $table
155
+     * @param \SimpleXMLElement $xml
156
+     * @throws \DomainException
157
+     */
158
+    private function loadField($table, $xml) {
159
+        $options = [ 'notnull' => false ];
160
+        foreach ($xml->children() as $child) {
161
+            /**
162
+             * @var \SimpleXMLElement $child
163
+             */
164
+            switch ($child->getName()) {
165
+                case 'name':
166
+                    $name = (string)$child;
167
+                    $name = $this->platform->quoteIdentifier($name);
168
+                    break;
169
+                case 'type':
170
+                    $type = (string)$child;
171
+                    switch ($type) {
172
+                        case 'text':
173
+                            $type = 'string';
174
+                            break;
175
+                        case 'clob':
176
+                            $type = 'text';
177
+                            break;
178
+                        case 'timestamp':
179
+                            $type = 'datetime';
180
+                            break;
181
+                        case 'numeric':
182
+                            $type = 'decimal';
183
+                            break;
184
+                    }
185
+                    break;
186
+                case 'length':
187
+                    $length = (string)$child;
188
+                    $options['length'] = $length;
189
+                    break;
190
+                case 'unsigned':
191
+                    $unsigned = $this->asBool($child);
192
+                    $options['unsigned'] = $unsigned;
193
+                    break;
194
+                case 'notnull':
195
+                    $notnull = $this->asBool($child);
196
+                    $options['notnull'] = $notnull;
197
+                    break;
198
+                case 'autoincrement':
199
+                    $autoincrement = $this->asBool($child);
200
+                    $options['autoincrement'] = $autoincrement;
201
+                    break;
202
+                case 'default':
203
+                    $default = (string)$child;
204
+                    $options['default'] = $default;
205
+                    break;
206
+                case 'comments':
207
+                    $comment = (string)$child;
208
+                    $options['comment'] = $comment;
209
+                    break;
210
+                case 'primary':
211
+                    $primary = $this->asBool($child);
212
+                    $options['primary'] = $primary;
213
+                    break;
214
+                case 'precision':
215
+                    $precision = (string)$child;
216
+                    $options['precision'] = $precision;
217
+                    break;
218
+                case 'scale':
219
+                    $scale = (string)$child;
220
+                    $options['scale'] = $scale;
221
+                    break;
222
+                default:
223
+                    throw new \DomainException('Unknown element: ' . $child->getName());
224 224
 
225
-			}
226
-		}
227
-		if (isset($name) && isset($type)) {
228
-			if (isset($options['default']) && empty($options['default'])) {
229
-				if (empty($options['notnull']) || !$options['notnull']) {
230
-					unset($options['default']);
231
-					$options['notnull'] = false;
232
-				} else {
233
-					$options['default'] = '';
234
-				}
235
-				if ($type == 'integer' || $type == 'decimal') {
236
-					$options['default'] = 0;
237
-				} elseif ($type == 'boolean') {
238
-					$options['default'] = false;
239
-				}
240
-				if (!empty($options['autoincrement']) && $options['autoincrement']) {
241
-					unset($options['default']);
242
-				}
243
-			}
244
-			if ($type === 'integer' && isset($options['default'])) {
245
-				$options['default'] = (int)$options['default'];
246
-			}
247
-			if ($type === 'integer' && isset($options['length'])) {
248
-				$length = $options['length'];
249
-				if ($length < 4) {
250
-					$type = 'smallint';
251
-				} elseif ($length > 4) {
252
-					$type = 'bigint';
253
-				}
254
-			}
255
-			if ($type === 'boolean' && isset($options['default'])) {
256
-				$options['default'] = $this->asBool($options['default']);
257
-			}
258
-			if (!empty($options['autoincrement'])
259
-				&& !empty($options['notnull'])
260
-			) {
261
-				$options['primary'] = true;
262
-			}
225
+            }
226
+        }
227
+        if (isset($name) && isset($type)) {
228
+            if (isset($options['default']) && empty($options['default'])) {
229
+                if (empty($options['notnull']) || !$options['notnull']) {
230
+                    unset($options['default']);
231
+                    $options['notnull'] = false;
232
+                } else {
233
+                    $options['default'] = '';
234
+                }
235
+                if ($type == 'integer' || $type == 'decimal') {
236
+                    $options['default'] = 0;
237
+                } elseif ($type == 'boolean') {
238
+                    $options['default'] = false;
239
+                }
240
+                if (!empty($options['autoincrement']) && $options['autoincrement']) {
241
+                    unset($options['default']);
242
+                }
243
+            }
244
+            if ($type === 'integer' && isset($options['default'])) {
245
+                $options['default'] = (int)$options['default'];
246
+            }
247
+            if ($type === 'integer' && isset($options['length'])) {
248
+                $length = $options['length'];
249
+                if ($length < 4) {
250
+                    $type = 'smallint';
251
+                } elseif ($length > 4) {
252
+                    $type = 'bigint';
253
+                }
254
+            }
255
+            if ($type === 'boolean' && isset($options['default'])) {
256
+                $options['default'] = $this->asBool($options['default']);
257
+            }
258
+            if (!empty($options['autoincrement'])
259
+                && !empty($options['notnull'])
260
+            ) {
261
+                $options['primary'] = true;
262
+            }
263 263
 
264
-			$table->addColumn($name, $type, $options);
265
-			if (!empty($options['primary']) && $options['primary']) {
266
-				$table->setPrimaryKey([$name]);
267
-			}
268
-		}
269
-	}
264
+            $table->addColumn($name, $type, $options);
265
+            if (!empty($options['primary']) && $options['primary']) {
266
+                $table->setPrimaryKey([$name]);
267
+            }
268
+        }
269
+    }
270 270
 
271
-	/**
272
-	 * @param \Doctrine\DBAL\Schema\Table $table
273
-	 * @param \SimpleXMLElement $xml
274
-	 * @throws \DomainException
275
-	 */
276
-	private function loadIndex($table, $xml) {
277
-		$name = null;
278
-		$fields = [];
279
-		foreach ($xml->children() as $child) {
280
-			/**
281
-			 * @var \SimpleXMLElement $child
282
-			 */
283
-			switch ($child->getName()) {
284
-				case 'name':
285
-					$name = (string)$child;
286
-					break;
287
-				case 'primary':
288
-					$primary = $this->asBool($child);
289
-					break;
290
-				case 'unique':
291
-					$unique = $this->asBool($child);
292
-					break;
293
-				case 'field':
294
-					foreach ($child->children() as $field) {
295
-						/**
296
-						 * @var \SimpleXMLElement $field
297
-						 */
298
-						switch ($field->getName()) {
299
-							case 'name':
300
-								$field_name = (string)$field;
301
-								$field_name = $this->platform->quoteIdentifier($field_name);
302
-								$fields[] = $field_name;
303
-								break;
304
-							case 'sorting':
305
-								break;
306
-							default:
307
-								throw new \DomainException('Unknown element: ' . $field->getName());
271
+    /**
272
+     * @param \Doctrine\DBAL\Schema\Table $table
273
+     * @param \SimpleXMLElement $xml
274
+     * @throws \DomainException
275
+     */
276
+    private function loadIndex($table, $xml) {
277
+        $name = null;
278
+        $fields = [];
279
+        foreach ($xml->children() as $child) {
280
+            /**
281
+             * @var \SimpleXMLElement $child
282
+             */
283
+            switch ($child->getName()) {
284
+                case 'name':
285
+                    $name = (string)$child;
286
+                    break;
287
+                case 'primary':
288
+                    $primary = $this->asBool($child);
289
+                    break;
290
+                case 'unique':
291
+                    $unique = $this->asBool($child);
292
+                    break;
293
+                case 'field':
294
+                    foreach ($child->children() as $field) {
295
+                        /**
296
+                         * @var \SimpleXMLElement $field
297
+                         */
298
+                        switch ($field->getName()) {
299
+                            case 'name':
300
+                                $field_name = (string)$field;
301
+                                $field_name = $this->platform->quoteIdentifier($field_name);
302
+                                $fields[] = $field_name;
303
+                                break;
304
+                            case 'sorting':
305
+                                break;
306
+                            default:
307
+                                throw new \DomainException('Unknown element: ' . $field->getName());
308 308
 
309
-						}
310
-					}
311
-					break;
312
-				default:
313
-					throw new \DomainException('Unknown element: ' . $child->getName());
309
+                        }
310
+                    }
311
+                    break;
312
+                default:
313
+                    throw new \DomainException('Unknown element: ' . $child->getName());
314 314
 
315
-			}
316
-		}
317
-		if (!empty($fields)) {
318
-			if (isset($primary) && $primary) {
319
-				if ($table->hasPrimaryKey()) {
320
-					return;
321
-				}
322
-				$table->setPrimaryKey($fields, $name);
323
-			} else {
324
-				if (isset($unique) && $unique) {
325
-					$table->addUniqueIndex($fields, $name);
326
-				} else {
327
-					$table->addIndex($fields, $name);
328
-				}
329
-			}
330
-		} else {
331
-			throw new \DomainException('Empty index definition: ' . $name . ' options:' . print_r($fields, true));
332
-		}
333
-	}
315
+            }
316
+        }
317
+        if (!empty($fields)) {
318
+            if (isset($primary) && $primary) {
319
+                if ($table->hasPrimaryKey()) {
320
+                    return;
321
+                }
322
+                $table->setPrimaryKey($fields, $name);
323
+            } else {
324
+                if (isset($unique) && $unique) {
325
+                    $table->addUniqueIndex($fields, $name);
326
+                } else {
327
+                    $table->addIndex($fields, $name);
328
+                }
329
+            }
330
+        } else {
331
+            throw new \DomainException('Empty index definition: ' . $name . ' options:' . print_r($fields, true));
332
+        }
333
+    }
334 334
 
335
-	/**
336
-	 * @param \SimpleXMLElement|string $xml
337
-	 * @return bool
338
-	 */
339
-	private function asBool($xml) {
340
-		$result = (string)$xml;
341
-		if ($result == 'true') {
342
-			$result = true;
343
-		} elseif ($result == 'false') {
344
-			$result = false;
345
-		}
346
-		return (bool)$result;
347
-	}
335
+    /**
336
+     * @param \SimpleXMLElement|string $xml
337
+     * @return bool
338
+     */
339
+    private function asBool($xml) {
340
+        $result = (string)$xml;
341
+        if ($result == 'true') {
342
+            $result = true;
343
+        } elseif ($result == 'false') {
344
+            $result = false;
345
+        }
346
+        return (bool)$result;
347
+    }
348 348
 }
Please login to merge, or discard this patch.
Spacing   +21 added lines, -21 removed lines patch added patch discarded remove patch
@@ -84,7 +84,7 @@  discard block
 block discarded – undo
84 84
 					$this->loadTable($schema, $child);
85 85
 					break;
86 86
 				default:
87
-					throw new \DomainException('Unknown element: ' . $child->getName());
87
+					throw new \DomainException('Unknown element: '.$child->getName());
88 88
 
89 89
 			}
90 90
 		}
@@ -104,7 +104,7 @@  discard block
 block discarded – undo
104 104
 			 */
105 105
 			switch ($child->getName()) {
106 106
 				case 'name':
107
-					$name = (string)$child;
107
+					$name = (string) $child;
108 108
 					$name = str_replace('*dbprefix*', $this->DBTABLEPREFIX, $name);
109 109
 					$name = $this->platform->quoteIdentifier($name);
110 110
 					$table = $schema->createTable($name);
@@ -120,7 +120,7 @@  discard block
 block discarded – undo
120 120
 					$this->loadDeclaration($table, $child);
121 121
 					break;
122 122
 				default:
123
-					throw new \DomainException('Unknown element: ' . $child->getName());
123
+					throw new \DomainException('Unknown element: '.$child->getName());
124 124
 
125 125
 			}
126 126
 		}
@@ -144,7 +144,7 @@  discard block
 block discarded – undo
144 144
 					$this->loadIndex($table, $child);
145 145
 					break;
146 146
 				default:
147
-					throw new \DomainException('Unknown element: ' . $child->getName());
147
+					throw new \DomainException('Unknown element: '.$child->getName());
148 148
 
149 149
 			}
150 150
 		}
@@ -156,18 +156,18 @@  discard block
 block discarded – undo
156 156
 	 * @throws \DomainException
157 157
 	 */
158 158
 	private function loadField($table, $xml) {
159
-		$options = [ 'notnull' => false ];
159
+		$options = ['notnull' => false];
160 160
 		foreach ($xml->children() as $child) {
161 161
 			/**
162 162
 			 * @var \SimpleXMLElement $child
163 163
 			 */
164 164
 			switch ($child->getName()) {
165 165
 				case 'name':
166
-					$name = (string)$child;
166
+					$name = (string) $child;
167 167
 					$name = $this->platform->quoteIdentifier($name);
168 168
 					break;
169 169
 				case 'type':
170
-					$type = (string)$child;
170
+					$type = (string) $child;
171 171
 					switch ($type) {
172 172
 						case 'text':
173 173
 							$type = 'string';
@@ -184,7 +184,7 @@  discard block
 block discarded – undo
184 184
 					}
185 185
 					break;
186 186
 				case 'length':
187
-					$length = (string)$child;
187
+					$length = (string) $child;
188 188
 					$options['length'] = $length;
189 189
 					break;
190 190
 				case 'unsigned':
@@ -200,11 +200,11 @@  discard block
 block discarded – undo
200 200
 					$options['autoincrement'] = $autoincrement;
201 201
 					break;
202 202
 				case 'default':
203
-					$default = (string)$child;
203
+					$default = (string) $child;
204 204
 					$options['default'] = $default;
205 205
 					break;
206 206
 				case 'comments':
207
-					$comment = (string)$child;
207
+					$comment = (string) $child;
208 208
 					$options['comment'] = $comment;
209 209
 					break;
210 210
 				case 'primary':
@@ -212,15 +212,15 @@  discard block
 block discarded – undo
212 212
 					$options['primary'] = $primary;
213 213
 					break;
214 214
 				case 'precision':
215
-					$precision = (string)$child;
215
+					$precision = (string) $child;
216 216
 					$options['precision'] = $precision;
217 217
 					break;
218 218
 				case 'scale':
219
-					$scale = (string)$child;
219
+					$scale = (string) $child;
220 220
 					$options['scale'] = $scale;
221 221
 					break;
222 222
 				default:
223
-					throw new \DomainException('Unknown element: ' . $child->getName());
223
+					throw new \DomainException('Unknown element: '.$child->getName());
224 224
 
225 225
 			}
226 226
 		}
@@ -242,7 +242,7 @@  discard block
 block discarded – undo
242 242
 				}
243 243
 			}
244 244
 			if ($type === 'integer' && isset($options['default'])) {
245
-				$options['default'] = (int)$options['default'];
245
+				$options['default'] = (int) $options['default'];
246 246
 			}
247 247
 			if ($type === 'integer' && isset($options['length'])) {
248 248
 				$length = $options['length'];
@@ -282,7 +282,7 @@  discard block
 block discarded – undo
282 282
 			 */
283 283
 			switch ($child->getName()) {
284 284
 				case 'name':
285
-					$name = (string)$child;
285
+					$name = (string) $child;
286 286
 					break;
287 287
 				case 'primary':
288 288
 					$primary = $this->asBool($child);
@@ -297,20 +297,20 @@  discard block
 block discarded – undo
297 297
 						 */
298 298
 						switch ($field->getName()) {
299 299
 							case 'name':
300
-								$field_name = (string)$field;
300
+								$field_name = (string) $field;
301 301
 								$field_name = $this->platform->quoteIdentifier($field_name);
302 302
 								$fields[] = $field_name;
303 303
 								break;
304 304
 							case 'sorting':
305 305
 								break;
306 306
 							default:
307
-								throw new \DomainException('Unknown element: ' . $field->getName());
307
+								throw new \DomainException('Unknown element: '.$field->getName());
308 308
 
309 309
 						}
310 310
 					}
311 311
 					break;
312 312
 				default:
313
-					throw new \DomainException('Unknown element: ' . $child->getName());
313
+					throw new \DomainException('Unknown element: '.$child->getName());
314 314
 
315 315
 			}
316 316
 		}
@@ -328,7 +328,7 @@  discard block
 block discarded – undo
328 328
 				}
329 329
 			}
330 330
 		} else {
331
-			throw new \DomainException('Empty index definition: ' . $name . ' options:' . print_r($fields, true));
331
+			throw new \DomainException('Empty index definition: '.$name.' options:'.print_r($fields, true));
332 332
 		}
333 333
 	}
334 334
 
@@ -337,12 +337,12 @@  discard block
 block discarded – undo
337 337
 	 * @return bool
338 338
 	 */
339 339
 	private function asBool($xml) {
340
-		$result = (string)$xml;
340
+		$result = (string) $xml;
341 341
 		if ($result == 'true') {
342 342
 			$result = true;
343 343
 		} elseif ($result == 'false') {
344 344
 			$result = false;
345 345
 		}
346
-		return (bool)$result;
346
+		return (bool) $result;
347 347
 	}
348 348
 }
Please login to merge, or discard this patch.
lib/private/DB/SchemaWrapper.php 2 patches
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -62,7 +62,7 @@  discard block
 block discarded – undo
62 62
 	 */
63 63
 	public function getTableNamesWithoutPrefix() {
64 64
 		$tableNames = $this->schema->getTableNames();
65
-		return array_map(function ($tableName) {
65
+		return array_map(function($tableName) {
66 66
 			if (strpos($tableName, $this->connection->getPrefix()) === 0) {
67 67
 				return substr($tableName, strlen($this->connection->getPrefix()));
68 68
 			}
@@ -80,7 +80,7 @@  discard block
 block discarded – undo
80 80
 	 * @throws \Doctrine\DBAL\Schema\SchemaException
81 81
 	 */
82 82
 	public function getTable($tableName) {
83
-		return $this->schema->getTable($this->connection->getPrefix() . $tableName);
83
+		return $this->schema->getTable($this->connection->getPrefix().$tableName);
84 84
 	}
85 85
 
86 86
 	/**
@@ -91,7 +91,7 @@  discard block
 block discarded – undo
91 91
 	 * @return boolean
92 92
 	 */
93 93
 	public function hasTable($tableName) {
94
-		return $this->schema->hasTable($this->connection->getPrefix() . $tableName);
94
+		return $this->schema->hasTable($this->connection->getPrefix().$tableName);
95 95
 	}
96 96
 
97 97
 	/**
@@ -101,7 +101,7 @@  discard block
 block discarded – undo
101 101
 	 * @return \Doctrine\DBAL\Schema\Table
102 102
 	 */
103 103
 	public function createTable($tableName) {
104
-		return $this->schema->createTable($this->connection->getPrefix() . $tableName);
104
+		return $this->schema->createTable($this->connection->getPrefix().$tableName);
105 105
 	}
106 106
 
107 107
 	/**
@@ -125,7 +125,7 @@  discard block
 block discarded – undo
125 125
 	 */
126 126
 	public function dropTable($tableName) {
127 127
 		$this->tablesToDelete[$tableName] = true;
128
-		return $this->schema->dropTable($this->connection->getPrefix() . $tableName);
128
+		return $this->schema->dropTable($this->connection->getPrefix().$tableName);
129 129
 	}
130 130
 
131 131
 	/**
Please login to merge, or discard this patch.
Indentation   +103 added lines, -103 removed lines patch added patch discarded remove patch
@@ -29,107 +29,107 @@
 block discarded – undo
29 29
 
30 30
 class SchemaWrapper implements ISchemaWrapper {
31 31
 
32
-	/** @var IDBConnection|Connection */
33
-	protected $connection;
34
-
35
-	/** @var Schema */
36
-	protected $schema;
37
-
38
-	/** @var array */
39
-	protected $tablesToDelete = [];
40
-
41
-	/**
42
-	 * @param IDBConnection $connection
43
-	 */
44
-	public function __construct(IDBConnection $connection) {
45
-		$this->connection = $connection;
46
-		$this->schema = $this->connection->createSchema();
47
-	}
48
-
49
-	public function getWrappedSchema() {
50
-		return $this->schema;
51
-	}
52
-
53
-	public function performDropTableCalls() {
54
-		foreach ($this->tablesToDelete as $tableName => $true) {
55
-			$this->connection->dropTable($tableName);
56
-			unset($this->tablesToDelete[$tableName]);
57
-		}
58
-	}
59
-
60
-	/**
61
-	 * Gets all table names
62
-	 *
63
-	 * @return array
64
-	 */
65
-	public function getTableNamesWithoutPrefix() {
66
-		$tableNames = $this->schema->getTableNames();
67
-		return array_map(function ($tableName) {
68
-			if (strpos($tableName, $this->connection->getPrefix()) === 0) {
69
-				return substr($tableName, strlen($this->connection->getPrefix()));
70
-			}
71
-
72
-			return $tableName;
73
-		}, $tableNames);
74
-	}
75
-
76
-	// Overwritten methods
77
-
78
-	/**
79
-	 * @return array
80
-	 */
81
-	public function getTableNames() {
82
-		return $this->schema->getTableNames();
83
-	}
84
-
85
-	/**
86
-	 * @param string $tableName
87
-	 *
88
-	 * @return \Doctrine\DBAL\Schema\Table
89
-	 * @throws \Doctrine\DBAL\Schema\SchemaException
90
-	 */
91
-	public function getTable($tableName) {
92
-		return $this->schema->getTable($this->connection->getPrefix() . $tableName);
93
-	}
94
-
95
-	/**
96
-	 * Does this schema have a table with the given name?
97
-	 *
98
-	 * @param string $tableName
99
-	 *
100
-	 * @return boolean
101
-	 */
102
-	public function hasTable($tableName) {
103
-		return $this->schema->hasTable($this->connection->getPrefix() . $tableName);
104
-	}
105
-
106
-	/**
107
-	 * Creates a new table.
108
-	 *
109
-	 * @param string $tableName
110
-	 * @return \Doctrine\DBAL\Schema\Table
111
-	 */
112
-	public function createTable($tableName) {
113
-		return $this->schema->createTable($this->connection->getPrefix() . $tableName);
114
-	}
115
-
116
-	/**
117
-	 * Drops a table from the schema.
118
-	 *
119
-	 * @param string $tableName
120
-	 * @return \Doctrine\DBAL\Schema\Schema
121
-	 */
122
-	public function dropTable($tableName) {
123
-		$this->tablesToDelete[$tableName] = true;
124
-		return $this->schema->dropTable($this->connection->getPrefix() . $tableName);
125
-	}
126
-
127
-	/**
128
-	 * Gets all tables of this schema.
129
-	 *
130
-	 * @return \Doctrine\DBAL\Schema\Table[]
131
-	 */
132
-	public function getTables() {
133
-		return $this->schema->getTables();
134
-	}
32
+    /** @var IDBConnection|Connection */
33
+    protected $connection;
34
+
35
+    /** @var Schema */
36
+    protected $schema;
37
+
38
+    /** @var array */
39
+    protected $tablesToDelete = [];
40
+
41
+    /**
42
+     * @param IDBConnection $connection
43
+     */
44
+    public function __construct(IDBConnection $connection) {
45
+        $this->connection = $connection;
46
+        $this->schema = $this->connection->createSchema();
47
+    }
48
+
49
+    public function getWrappedSchema() {
50
+        return $this->schema;
51
+    }
52
+
53
+    public function performDropTableCalls() {
54
+        foreach ($this->tablesToDelete as $tableName => $true) {
55
+            $this->connection->dropTable($tableName);
56
+            unset($this->tablesToDelete[$tableName]);
57
+        }
58
+    }
59
+
60
+    /**
61
+     * Gets all table names
62
+     *
63
+     * @return array
64
+     */
65
+    public function getTableNamesWithoutPrefix() {
66
+        $tableNames = $this->schema->getTableNames();
67
+        return array_map(function ($tableName) {
68
+            if (strpos($tableName, $this->connection->getPrefix()) === 0) {
69
+                return substr($tableName, strlen($this->connection->getPrefix()));
70
+            }
71
+
72
+            return $tableName;
73
+        }, $tableNames);
74
+    }
75
+
76
+    // Overwritten methods
77
+
78
+    /**
79
+     * @return array
80
+     */
81
+    public function getTableNames() {
82
+        return $this->schema->getTableNames();
83
+    }
84
+
85
+    /**
86
+     * @param string $tableName
87
+     *
88
+     * @return \Doctrine\DBAL\Schema\Table
89
+     * @throws \Doctrine\DBAL\Schema\SchemaException
90
+     */
91
+    public function getTable($tableName) {
92
+        return $this->schema->getTable($this->connection->getPrefix() . $tableName);
93
+    }
94
+
95
+    /**
96
+     * Does this schema have a table with the given name?
97
+     *
98
+     * @param string $tableName
99
+     *
100
+     * @return boolean
101
+     */
102
+    public function hasTable($tableName) {
103
+        return $this->schema->hasTable($this->connection->getPrefix() . $tableName);
104
+    }
105
+
106
+    /**
107
+     * Creates a new table.
108
+     *
109
+     * @param string $tableName
110
+     * @return \Doctrine\DBAL\Schema\Table
111
+     */
112
+    public function createTable($tableName) {
113
+        return $this->schema->createTable($this->connection->getPrefix() . $tableName);
114
+    }
115
+
116
+    /**
117
+     * Drops a table from the schema.
118
+     *
119
+     * @param string $tableName
120
+     * @return \Doctrine\DBAL\Schema\Schema
121
+     */
122
+    public function dropTable($tableName) {
123
+        $this->tablesToDelete[$tableName] = true;
124
+        return $this->schema->dropTable($this->connection->getPrefix() . $tableName);
125
+    }
126
+
127
+    /**
128
+     * Gets all tables of this schema.
129
+     *
130
+     * @return \Doctrine\DBAL\Schema\Table[]
131
+     */
132
+    public function getTables() {
133
+        return $this->schema->getTables();
134
+    }
135 135
 }
Please login to merge, or discard this patch.
lib/private/DB/OracleConnection.php 2 patches
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -82,7 +82,7 @@  discard block
 block discarded – undo
82 82
 	 * @param string $table table name without the prefix
83 83
 	 */
84 84
 	public function dropTable($table) {
85
-		$table = $this->tablePrefix . trim($table);
85
+		$table = $this->tablePrefix.trim($table);
86 86
 		$table = $this->quoteIdentifier($table);
87 87
 		$schema = $this->getSchemaManager();
88 88
 		if ($schema->tablesExist([$table])) {
@@ -97,7 +97,7 @@  discard block
 block discarded – undo
97 97
 	 * @return bool
98 98
 	 */
99 99
 	public function tableExists($table) {
100
-		$table = $this->tablePrefix . trim($table);
100
+		$table = $this->tablePrefix.trim($table);
101 101
 		$table = $this->quoteIdentifier($table);
102 102
 		$schema = $this->getSchemaManager();
103 103
 		return $schema->tablesExist([$table]);
Please login to merge, or discard this patch.
Indentation   +71 added lines, -71 removed lines patch added patch discarded remove patch
@@ -28,80 +28,80 @@
 block discarded – undo
28 28
 namespace OC\DB;
29 29
 
30 30
 class OracleConnection extends Connection {
31
-	/**
32
-	 * Quote the keys of the array
33
-	 */
34
-	private function quoteKeys(array $data) {
35
-		$return = [];
36
-		$c = $this->getDatabasePlatform()->getIdentifierQuoteCharacter();
37
-		foreach ($data as $key => $value) {
38
-			if ($key[0] !== $c) {
39
-				$return[$this->quoteIdentifier($key)] = $value;
40
-			} else {
41
-				$return[$key] = $value;
42
-			}
43
-		}
44
-		return $return;
45
-	}
31
+    /**
32
+     * Quote the keys of the array
33
+     */
34
+    private function quoteKeys(array $data) {
35
+        $return = [];
36
+        $c = $this->getDatabasePlatform()->getIdentifierQuoteCharacter();
37
+        foreach ($data as $key => $value) {
38
+            if ($key[0] !== $c) {
39
+                $return[$this->quoteIdentifier($key)] = $value;
40
+            } else {
41
+                $return[$key] = $value;
42
+            }
43
+        }
44
+        return $return;
45
+    }
46 46
 
47
-	/**
48
-	 * {@inheritDoc}
49
-	 */
50
-	public function insert($table, array $data, array $types = []) {
51
-		if ($table[0] !== $this->getDatabasePlatform()->getIdentifierQuoteCharacter()) {
52
-			$table = $this->quoteIdentifier($table);
53
-		}
54
-		$data = $this->quoteKeys($data);
55
-		return parent::insert($table, $data, $types);
56
-	}
47
+    /**
48
+     * {@inheritDoc}
49
+     */
50
+    public function insert($table, array $data, array $types = []) {
51
+        if ($table[0] !== $this->getDatabasePlatform()->getIdentifierQuoteCharacter()) {
52
+            $table = $this->quoteIdentifier($table);
53
+        }
54
+        $data = $this->quoteKeys($data);
55
+        return parent::insert($table, $data, $types);
56
+    }
57 57
 
58
-	/**
59
-	 * {@inheritDoc}
60
-	 */
61
-	public function update($table, array $data, array $criteria, array $types = []) {
62
-		if ($table[0] !== $this->getDatabasePlatform()->getIdentifierQuoteCharacter()) {
63
-			$table = $this->quoteIdentifier($table);
64
-		}
65
-		$data = $this->quoteKeys($data);
66
-		$criteria = $this->quoteKeys($criteria);
67
-		return parent::update($table, $data, $criteria, $types);
68
-	}
58
+    /**
59
+     * {@inheritDoc}
60
+     */
61
+    public function update($table, array $data, array $criteria, array $types = []) {
62
+        if ($table[0] !== $this->getDatabasePlatform()->getIdentifierQuoteCharacter()) {
63
+            $table = $this->quoteIdentifier($table);
64
+        }
65
+        $data = $this->quoteKeys($data);
66
+        $criteria = $this->quoteKeys($criteria);
67
+        return parent::update($table, $data, $criteria, $types);
68
+    }
69 69
 
70
-	/**
71
-	 * {@inheritDoc}
72
-	 */
73
-	public function delete($table, array $criteria, array $types = []) {
74
-		if ($table[0] !== $this->getDatabasePlatform()->getIdentifierQuoteCharacter()) {
75
-			$table = $this->quoteIdentifier($table);
76
-		}
77
-		$criteria = $this->quoteKeys($criteria);
78
-		return parent::delete($table, $criteria);
79
-	}
70
+    /**
71
+     * {@inheritDoc}
72
+     */
73
+    public function delete($table, array $criteria, array $types = []) {
74
+        if ($table[0] !== $this->getDatabasePlatform()->getIdentifierQuoteCharacter()) {
75
+            $table = $this->quoteIdentifier($table);
76
+        }
77
+        $criteria = $this->quoteKeys($criteria);
78
+        return parent::delete($table, $criteria);
79
+    }
80 80
 
81
-	/**
82
-	 * Drop a table from the database if it exists
83
-	 *
84
-	 * @param string $table table name without the prefix
85
-	 */
86
-	public function dropTable($table) {
87
-		$table = $this->tablePrefix . trim($table);
88
-		$table = $this->quoteIdentifier($table);
89
-		$schema = $this->getSchemaManager();
90
-		if ($schema->tablesExist([$table])) {
91
-			$schema->dropTable($table);
92
-		}
93
-	}
81
+    /**
82
+     * Drop a table from the database if it exists
83
+     *
84
+     * @param string $table table name without the prefix
85
+     */
86
+    public function dropTable($table) {
87
+        $table = $this->tablePrefix . trim($table);
88
+        $table = $this->quoteIdentifier($table);
89
+        $schema = $this->getSchemaManager();
90
+        if ($schema->tablesExist([$table])) {
91
+            $schema->dropTable($table);
92
+        }
93
+    }
94 94
 
95
-	/**
96
-	 * Check if a table exists
97
-	 *
98
-	 * @param string $table table name without the prefix
99
-	 * @return bool
100
-	 */
101
-	public function tableExists($table) {
102
-		$table = $this->tablePrefix . trim($table);
103
-		$table = $this->quoteIdentifier($table);
104
-		$schema = $this->getSchemaManager();
105
-		return $schema->tablesExist([$table]);
106
-	}
95
+    /**
96
+     * Check if a table exists
97
+     *
98
+     * @param string $table table name without the prefix
99
+     * @return bool
100
+     */
101
+    public function tableExists($table) {
102
+        $table = $this->tablePrefix . trim($table);
103
+        $table = $this->quoteIdentifier($table);
104
+        $schema = $this->getSchemaManager();
105
+        return $schema->tablesExist([$table]);
106
+    }
107 107
 }
Please login to merge, or discard this patch.
lib/private/DB/Connection.php 2 patches
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -59,7 +59,7 @@  discard block
 block discarded – undo
59 59
 			return parent::connect();
60 60
 		} catch (DBALException $e) {
61 61
 			// throw a new exception to prevent leaking info from the stacktrace
62
-			throw new DBALException('Failed to connect to the database: ' . $e->getMessage(), $e->getCode());
62
+			throw new DBALException('Failed to connect to the database: '.$e->getMessage(), $e->getCode());
63 63
 		}
64 64
 	}
65 65
 
@@ -111,7 +111,7 @@  discard block
 block discarded – undo
111 111
 		// 0 is the method where we use `getCallerBacktrace`
112 112
 		// 1 is the target method which uses the method we want to log
113 113
 		if (isset($traces[1])) {
114
-			return $traces[1]['file'] . ':' . $traces[1]['line'];
114
+			return $traces[1]['file'].':'.$traces[1]['line'];
115 115
 		}
116 116
 
117 117
 		return '';
@@ -280,7 +280,7 @@  discard block
 block discarded – undo
280 280
 			$insertQb = $this->getQueryBuilder();
281 281
 			$insertQb->insert($table)
282 282
 				->values(
283
-					array_map(function ($value) use ($insertQb) {
283
+					array_map(function($value) use ($insertQb) {
284 284
 						return $insertQb->createNamedParameter($value, $this->getType($value));
285 285
 					}, array_merge($keys, $values))
286 286
 				);
@@ -324,7 +324,7 @@  discard block
 block discarded – undo
324 324
 			throw new \BadMethodCallException('Can not lock a new table until the previous lock is released.');
325 325
 		}
326 326
 
327
-		$tableName = $this->tablePrefix . $tableName;
327
+		$tableName = $this->tablePrefix.$tableName;
328 328
 		$this->lockedTable = $tableName;
329 329
 		$this->adapter->lockTable($tableName);
330 330
 	}
@@ -345,11 +345,11 @@  discard block
 block discarded – undo
345 345
 	 * @return string
346 346
 	 */
347 347
 	public function getError() {
348
-		$msg = $this->errorCode() . ': ';
348
+		$msg = $this->errorCode().': ';
349 349
 		$errorInfo = $this->errorInfo();
350 350
 		if (is_array($errorInfo)) {
351
-			$msg .= 'SQLSTATE = '.$errorInfo[0] . ', ';
352
-			$msg .= 'Driver Code = '.$errorInfo[1] . ', ';
351
+			$msg .= 'SQLSTATE = '.$errorInfo[0].', ';
352
+			$msg .= 'Driver Code = '.$errorInfo[1].', ';
353 353
 			$msg .= 'Driver Message = '.$errorInfo[2];
354 354
 		}
355 355
 		return $msg;
@@ -361,7 +361,7 @@  discard block
 block discarded – undo
361 361
 	 * @param string $table table name without the prefix
362 362
 	 */
363 363
 	public function dropTable($table) {
364
-		$table = $this->tablePrefix . trim($table);
364
+		$table = $this->tablePrefix.trim($table);
365 365
 		$schema = $this->getSchemaManager();
366 366
 		if ($schema->tablesExist([$table])) {
367 367
 			$schema->dropTable($table);
@@ -375,7 +375,7 @@  discard block
 block discarded – undo
375 375
 	 * @return bool
376 376
 	 */
377 377
 	public function tableExists($table) {
378
-		$table = $this->tablePrefix . trim($table);
378
+		$table = $this->tablePrefix.trim($table);
379 379
 		$schema = $this->getSchemaManager();
380 380
 		return $schema->tablesExist([$table]);
381 381
 	}
Please login to merge, or discard this patch.
Indentation   +440 added lines, -440 removed lines patch added patch discarded remove patch
@@ -50,444 +50,444 @@
 block discarded – undo
50 50
 use OCP\PreConditionNotMetException;
51 51
 
52 52
 class Connection extends ReconnectWrapper implements IDBConnection {
53
-	/** @var string */
54
-	protected $tablePrefix;
55
-
56
-	/** @var \OC\DB\Adapter $adapter */
57
-	protected $adapter;
58
-
59
-	/** @var SystemConfig */
60
-	private $systemConfig;
61
-
62
-	/** @var ILogger */
63
-	private $logger;
64
-
65
-	protected $lockedTable = null;
66
-
67
-	/** @var int */
68
-	protected $queriesBuilt = 0;
69
-
70
-	/** @var int */
71
-	protected $queriesExecuted = 0;
72
-
73
-	public function connect() {
74
-		try {
75
-			return parent::connect();
76
-		} catch (DBALException $e) {
77
-			// throw a new exception to prevent leaking info from the stacktrace
78
-			throw new DBALException('Failed to connect to the database: ' . $e->getMessage(), $e->getCode());
79
-		}
80
-	}
81
-
82
-	public function getStats(): array {
83
-		return [
84
-			'built' => $this->queriesBuilt,
85
-			'executed' => $this->queriesExecuted,
86
-		];
87
-	}
88
-
89
-	/**
90
-	 * Returns a QueryBuilder for the connection.
91
-	 *
92
-	 * @return \OCP\DB\QueryBuilder\IQueryBuilder
93
-	 */
94
-	public function getQueryBuilder() {
95
-		$this->queriesBuilt++;
96
-		return new QueryBuilder(
97
-			$this,
98
-			$this->systemConfig,
99
-			$this->logger
100
-		);
101
-	}
102
-
103
-	/**
104
-	 * Gets the QueryBuilder for the connection.
105
-	 *
106
-	 * @return \Doctrine\DBAL\Query\QueryBuilder
107
-	 * @deprecated please use $this->getQueryBuilder() instead
108
-	 */
109
-	public function createQueryBuilder() {
110
-		$backtrace = $this->getCallerBacktrace();
111
-		\OC::$server->getLogger()->debug('Doctrine QueryBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
112
-		$this->queriesBuilt++;
113
-		return parent::createQueryBuilder();
114
-	}
115
-
116
-	/**
117
-	 * Gets the ExpressionBuilder for the connection.
118
-	 *
119
-	 * @return \Doctrine\DBAL\Query\Expression\ExpressionBuilder
120
-	 * @deprecated please use $this->getQueryBuilder()->expr() instead
121
-	 */
122
-	public function getExpressionBuilder() {
123
-		$backtrace = $this->getCallerBacktrace();
124
-		\OC::$server->getLogger()->debug('Doctrine ExpressionBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
125
-		$this->queriesBuilt++;
126
-		return parent::getExpressionBuilder();
127
-	}
128
-
129
-	/**
130
-	 * Get the file and line that called the method where `getCallerBacktrace()` was used
131
-	 *
132
-	 * @return string
133
-	 */
134
-	protected function getCallerBacktrace() {
135
-		$traces = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
136
-
137
-		// 0 is the method where we use `getCallerBacktrace`
138
-		// 1 is the target method which uses the method we want to log
139
-		if (isset($traces[1])) {
140
-			return $traces[1]['file'] . ':' . $traces[1]['line'];
141
-		}
142
-
143
-		return '';
144
-	}
145
-
146
-	/**
147
-	 * @return string
148
-	 */
149
-	public function getPrefix() {
150
-		return $this->tablePrefix;
151
-	}
152
-
153
-	/**
154
-	 * Initializes a new instance of the Connection class.
155
-	 *
156
-	 * @param array $params  The connection parameters.
157
-	 * @param \Doctrine\DBAL\Driver $driver
158
-	 * @param \Doctrine\DBAL\Configuration $config
159
-	 * @param \Doctrine\Common\EventManager $eventManager
160
-	 * @throws \Exception
161
-	 */
162
-	public function __construct(array $params, Driver $driver, Configuration $config = null,
163
-		EventManager $eventManager = null) {
164
-		if (!isset($params['adapter'])) {
165
-			throw new \Exception('adapter not set');
166
-		}
167
-		if (!isset($params['tablePrefix'])) {
168
-			throw new \Exception('tablePrefix not set');
169
-		}
170
-		parent::__construct($params, $driver, $config, $eventManager);
171
-		$this->adapter = new $params['adapter']($this);
172
-		$this->tablePrefix = $params['tablePrefix'];
173
-
174
-		$this->systemConfig = \OC::$server->getSystemConfig();
175
-		$this->logger = \OC::$server->getLogger();
176
-	}
177
-
178
-	/**
179
-	 * Prepares an SQL statement.
180
-	 *
181
-	 * @param string $statement The SQL statement to prepare.
182
-	 * @param int $limit
183
-	 * @param int $offset
184
-	 * @return \Doctrine\DBAL\Driver\Statement The prepared statement.
185
-	 */
186
-	public function prepare($statement, $limit = null, $offset = null) {
187
-		if ($limit === -1) {
188
-			$limit = null;
189
-		}
190
-		if (!is_null($limit)) {
191
-			$platform = $this->getDatabasePlatform();
192
-			$statement = $platform->modifyLimitQuery($statement, $limit, $offset);
193
-		}
194
-		$statement = $this->replaceTablePrefix($statement);
195
-		$statement = $this->adapter->fixupStatement($statement);
196
-
197
-		return parent::prepare($statement);
198
-	}
199
-
200
-	/**
201
-	 * Executes an, optionally parametrized, SQL query.
202
-	 *
203
-	 * If the query is parametrized, a prepared statement is used.
204
-	 * If an SQLLogger is configured, the execution is logged.
205
-	 *
206
-	 * @param string                                      $sql  The SQL query to execute.
207
-	 * @param array                                       $params The parameters to bind to the query, if any.
208
-	 * @param array                                       $types  The types the previous parameters are in.
209
-	 * @param \Doctrine\DBAL\Cache\QueryCacheProfile|null $qcp    The query cache profile, optional.
210
-	 *
211
-	 * @return \Doctrine\DBAL\Driver\Statement The executed statement.
212
-	 *
213
-	 * @throws \Doctrine\DBAL\DBALException
214
-	 */
215
-	public function executeQuery($sql, array $params = [], $types = [], QueryCacheProfile $qcp = null) {
216
-		$sql = $this->replaceTablePrefix($sql);
217
-		$sql = $this->adapter->fixupStatement($sql);
218
-		$this->queriesExecuted++;
219
-		return parent::executeQuery($sql, $params, $types, $qcp);
220
-	}
221
-
222
-	public function executeUpdate($sql, array $params = [], array $types = []) {
223
-		$sql = $this->replaceTablePrefix($sql);
224
-		$sql = $this->adapter->fixupStatement($sql);
225
-		$this->queriesExecuted++;
226
-		return parent::executeUpdate($sql, $params, $types);
227
-	}
228
-
229
-	/**
230
-	 * Executes an SQL INSERT/UPDATE/DELETE query with the given parameters
231
-	 * and returns the number of affected rows.
232
-	 *
233
-	 * This method supports PDO binding types as well as DBAL mapping types.
234
-	 *
235
-	 * @param string $sql  The SQL query.
236
-	 * @param array  $params The query parameters.
237
-	 * @param array  $types  The parameter types.
238
-	 *
239
-	 * @return integer The number of affected rows.
240
-	 *
241
-	 * @throws \Doctrine\DBAL\DBALException
242
-	 */
243
-	public function executeStatement($sql, array $params = [], array $types = []) {
244
-		$sql = $this->replaceTablePrefix($sql);
245
-		$sql = $this->adapter->fixupStatement($sql);
246
-		$this->queriesExecuted++;
247
-		return parent::executeStatement($sql, $params, $types);
248
-	}
249
-
250
-	/**
251
-	 * Returns the ID of the last inserted row, or the last value from a sequence object,
252
-	 * depending on the underlying driver.
253
-	 *
254
-	 * Note: This method may not return a meaningful or consistent result across different drivers,
255
-	 * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY
256
-	 * columns or sequences.
257
-	 *
258
-	 * @param string $seqName Name of the sequence object from which the ID should be returned.
259
-	 * @return string A string representation of the last inserted ID.
260
-	 */
261
-	public function lastInsertId($seqName = null) {
262
-		if ($seqName) {
263
-			$seqName = $this->replaceTablePrefix($seqName);
264
-		}
265
-		return $this->adapter->lastInsertId($seqName);
266
-	}
267
-
268
-	// internal use
269
-	public function realLastInsertId($seqName = null) {
270
-		return parent::lastInsertId($seqName);
271
-	}
272
-
273
-	/**
274
-	 * Insert a row if the matching row does not exists. To accomplish proper race condition avoidance
275
-	 * it is needed that there is also a unique constraint on the values. Then this method will
276
-	 * catch the exception and return 0.
277
-	 *
278
-	 * @param string $table The table name (will replace *PREFIX* with the actual prefix)
279
-	 * @param array $input data that should be inserted into the table  (column name => value)
280
-	 * @param array|null $compare List of values that should be checked for "if not exists"
281
-	 *				If this is null or an empty array, all keys of $input will be compared
282
-	 *				Please note: text fields (clob) must not be used in the compare array
283
-	 * @return int number of inserted rows
284
-	 * @throws \Doctrine\DBAL\DBALException
285
-	 * @deprecated 15.0.0 - use unique index and "try { $db->insert() } catch (UniqueConstraintViolationException $e) {}" instead, because it is more reliable and does not have the risk for deadlocks - see https://github.com/nextcloud/server/pull/12371
286
-	 */
287
-	public function insertIfNotExist($table, $input, array $compare = null) {
288
-		return $this->adapter->insertIfNotExist($table, $input, $compare);
289
-	}
290
-
291
-	public function insertIgnoreConflict(string $table, array $values) : int {
292
-		return $this->adapter->insertIgnoreConflict($table, $values);
293
-	}
294
-
295
-	private function getType($value) {
296
-		if (is_bool($value)) {
297
-			return IQueryBuilder::PARAM_BOOL;
298
-		} elseif (is_int($value)) {
299
-			return IQueryBuilder::PARAM_INT;
300
-		} else {
301
-			return IQueryBuilder::PARAM_STR;
302
-		}
303
-	}
304
-
305
-	/**
306
-	 * Insert or update a row value
307
-	 *
308
-	 * @param string $table
309
-	 * @param array $keys (column name => value)
310
-	 * @param array $values (column name => value)
311
-	 * @param array $updatePreconditionValues ensure values match preconditions (column name => value)
312
-	 * @return int number of new rows
313
-	 * @throws \Doctrine\DBAL\DBALException
314
-	 * @throws PreConditionNotMetException
315
-	 */
316
-	public function setValues($table, array $keys, array $values, array $updatePreconditionValues = []) {
317
-		try {
318
-			$insertQb = $this->getQueryBuilder();
319
-			$insertQb->insert($table)
320
-				->values(
321
-					array_map(function ($value) use ($insertQb) {
322
-						return $insertQb->createNamedParameter($value, $this->getType($value));
323
-					}, array_merge($keys, $values))
324
-				);
325
-			return $insertQb->execute();
326
-		} catch (NotNullConstraintViolationException $e) {
327
-			throw $e;
328
-		} catch (ConstraintViolationException $e) {
329
-			// value already exists, try update
330
-			$updateQb = $this->getQueryBuilder();
331
-			$updateQb->update($table);
332
-			foreach ($values as $name => $value) {
333
-				$updateQb->set($name, $updateQb->createNamedParameter($value, $this->getType($value)));
334
-			}
335
-			$where = $updateQb->expr()->andX();
336
-			$whereValues = array_merge($keys, $updatePreconditionValues);
337
-			foreach ($whereValues as $name => $value) {
338
-				if ($value === '') {
339
-					$where->add($updateQb->expr()->emptyString(
340
-						$name
341
-					));
342
-				} else {
343
-					$where->add($updateQb->expr()->eq(
344
-						$name,
345
-						$updateQb->createNamedParameter($value, $this->getType($value)),
346
-						$this->getType($value)
347
-					));
348
-				}
349
-			}
350
-			$updateQb->where($where);
351
-			$affected = $updateQb->execute();
352
-
353
-			if ($affected === 0 && !empty($updatePreconditionValues)) {
354
-				throw new PreConditionNotMetException();
355
-			}
356
-
357
-			return 0;
358
-		}
359
-	}
360
-
361
-	/**
362
-	 * Create an exclusive read+write lock on a table
363
-	 *
364
-	 * @param string $tableName
365
-	 * @throws \BadMethodCallException When trying to acquire a second lock
366
-	 * @since 9.1.0
367
-	 */
368
-	public function lockTable($tableName) {
369
-		if ($this->lockedTable !== null) {
370
-			throw new \BadMethodCallException('Can not lock a new table until the previous lock is released.');
371
-		}
372
-
373
-		$tableName = $this->tablePrefix . $tableName;
374
-		$this->lockedTable = $tableName;
375
-		$this->adapter->lockTable($tableName);
376
-	}
377
-
378
-	/**
379
-	 * Release a previous acquired lock again
380
-	 *
381
-	 * @since 9.1.0
382
-	 */
383
-	public function unlockTable() {
384
-		$this->adapter->unlockTable();
385
-		$this->lockedTable = null;
386
-	}
387
-
388
-	/**
389
-	 * returns the error code and message as a string for logging
390
-	 * works with DoctrineException
391
-	 * @return string
392
-	 */
393
-	public function getError() {
394
-		$msg = $this->errorCode() . ': ';
395
-		$errorInfo = $this->errorInfo();
396
-		if (is_array($errorInfo)) {
397
-			$msg .= 'SQLSTATE = '.$errorInfo[0] . ', ';
398
-			$msg .= 'Driver Code = '.$errorInfo[1] . ', ';
399
-			$msg .= 'Driver Message = '.$errorInfo[2];
400
-		}
401
-		return $msg;
402
-	}
403
-
404
-	/**
405
-	 * Drop a table from the database if it exists
406
-	 *
407
-	 * @param string $table table name without the prefix
408
-	 */
409
-	public function dropTable($table) {
410
-		$table = $this->tablePrefix . trim($table);
411
-		$schema = $this->getSchemaManager();
412
-		if ($schema->tablesExist([$table])) {
413
-			$schema->dropTable($table);
414
-		}
415
-	}
416
-
417
-	/**
418
-	 * Check if a table exists
419
-	 *
420
-	 * @param string $table table name without the prefix
421
-	 * @return bool
422
-	 */
423
-	public function tableExists($table) {
424
-		$table = $this->tablePrefix . trim($table);
425
-		$schema = $this->getSchemaManager();
426
-		return $schema->tablesExist([$table]);
427
-	}
428
-
429
-	// internal use
430
-	/**
431
-	 * @param string $statement
432
-	 * @return string
433
-	 */
434
-	protected function replaceTablePrefix($statement) {
435
-		return str_replace('*PREFIX*', $this->tablePrefix, $statement);
436
-	}
437
-
438
-	/**
439
-	 * Check if a transaction is active
440
-	 *
441
-	 * @return bool
442
-	 * @since 8.2.0
443
-	 */
444
-	public function inTransaction() {
445
-		return $this->getTransactionNestingLevel() > 0;
446
-	}
447
-
448
-	/**
449
-	 * Escape a parameter to be used in a LIKE query
450
-	 *
451
-	 * @param string $param
452
-	 * @return string
453
-	 */
454
-	public function escapeLikeParameter($param) {
455
-		return addcslashes($param, '\\_%');
456
-	}
457
-
458
-	/**
459
-	 * Check whether or not the current database support 4byte wide unicode
460
-	 *
461
-	 * @return bool
462
-	 * @since 11.0.0
463
-	 */
464
-	public function supports4ByteText() {
465
-		if (!$this->getDatabasePlatform() instanceof MySqlPlatform) {
466
-			return true;
467
-		}
468
-		return $this->getParams()['charset'] === 'utf8mb4';
469
-	}
470
-
471
-
472
-	/**
473
-	 * Create the schema of the connected database
474
-	 *
475
-	 * @return Schema
476
-	 */
477
-	public function createSchema() {
478
-		$schemaManager = new MDB2SchemaManager($this);
479
-		$migrator = $schemaManager->getMigrator();
480
-		return $migrator->createSchema();
481
-	}
482
-
483
-	/**
484
-	 * Migrate the database to the given schema
485
-	 *
486
-	 * @param Schema $toSchema
487
-	 */
488
-	public function migrateToSchema(Schema $toSchema) {
489
-		$schemaManager = new MDB2SchemaManager($this);
490
-		$migrator = $schemaManager->getMigrator();
491
-		$migrator->migrate($toSchema);
492
-	}
53
+    /** @var string */
54
+    protected $tablePrefix;
55
+
56
+    /** @var \OC\DB\Adapter $adapter */
57
+    protected $adapter;
58
+
59
+    /** @var SystemConfig */
60
+    private $systemConfig;
61
+
62
+    /** @var ILogger */
63
+    private $logger;
64
+
65
+    protected $lockedTable = null;
66
+
67
+    /** @var int */
68
+    protected $queriesBuilt = 0;
69
+
70
+    /** @var int */
71
+    protected $queriesExecuted = 0;
72
+
73
+    public function connect() {
74
+        try {
75
+            return parent::connect();
76
+        } catch (DBALException $e) {
77
+            // throw a new exception to prevent leaking info from the stacktrace
78
+            throw new DBALException('Failed to connect to the database: ' . $e->getMessage(), $e->getCode());
79
+        }
80
+    }
81
+
82
+    public function getStats(): array {
83
+        return [
84
+            'built' => $this->queriesBuilt,
85
+            'executed' => $this->queriesExecuted,
86
+        ];
87
+    }
88
+
89
+    /**
90
+     * Returns a QueryBuilder for the connection.
91
+     *
92
+     * @return \OCP\DB\QueryBuilder\IQueryBuilder
93
+     */
94
+    public function getQueryBuilder() {
95
+        $this->queriesBuilt++;
96
+        return new QueryBuilder(
97
+            $this,
98
+            $this->systemConfig,
99
+            $this->logger
100
+        );
101
+    }
102
+
103
+    /**
104
+     * Gets the QueryBuilder for the connection.
105
+     *
106
+     * @return \Doctrine\DBAL\Query\QueryBuilder
107
+     * @deprecated please use $this->getQueryBuilder() instead
108
+     */
109
+    public function createQueryBuilder() {
110
+        $backtrace = $this->getCallerBacktrace();
111
+        \OC::$server->getLogger()->debug('Doctrine QueryBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
112
+        $this->queriesBuilt++;
113
+        return parent::createQueryBuilder();
114
+    }
115
+
116
+    /**
117
+     * Gets the ExpressionBuilder for the connection.
118
+     *
119
+     * @return \Doctrine\DBAL\Query\Expression\ExpressionBuilder
120
+     * @deprecated please use $this->getQueryBuilder()->expr() instead
121
+     */
122
+    public function getExpressionBuilder() {
123
+        $backtrace = $this->getCallerBacktrace();
124
+        \OC::$server->getLogger()->debug('Doctrine ExpressionBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
125
+        $this->queriesBuilt++;
126
+        return parent::getExpressionBuilder();
127
+    }
128
+
129
+    /**
130
+     * Get the file and line that called the method where `getCallerBacktrace()` was used
131
+     *
132
+     * @return string
133
+     */
134
+    protected function getCallerBacktrace() {
135
+        $traces = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
136
+
137
+        // 0 is the method where we use `getCallerBacktrace`
138
+        // 1 is the target method which uses the method we want to log
139
+        if (isset($traces[1])) {
140
+            return $traces[1]['file'] . ':' . $traces[1]['line'];
141
+        }
142
+
143
+        return '';
144
+    }
145
+
146
+    /**
147
+     * @return string
148
+     */
149
+    public function getPrefix() {
150
+        return $this->tablePrefix;
151
+    }
152
+
153
+    /**
154
+     * Initializes a new instance of the Connection class.
155
+     *
156
+     * @param array $params  The connection parameters.
157
+     * @param \Doctrine\DBAL\Driver $driver
158
+     * @param \Doctrine\DBAL\Configuration $config
159
+     * @param \Doctrine\Common\EventManager $eventManager
160
+     * @throws \Exception
161
+     */
162
+    public function __construct(array $params, Driver $driver, Configuration $config = null,
163
+        EventManager $eventManager = null) {
164
+        if (!isset($params['adapter'])) {
165
+            throw new \Exception('adapter not set');
166
+        }
167
+        if (!isset($params['tablePrefix'])) {
168
+            throw new \Exception('tablePrefix not set');
169
+        }
170
+        parent::__construct($params, $driver, $config, $eventManager);
171
+        $this->adapter = new $params['adapter']($this);
172
+        $this->tablePrefix = $params['tablePrefix'];
173
+
174
+        $this->systemConfig = \OC::$server->getSystemConfig();
175
+        $this->logger = \OC::$server->getLogger();
176
+    }
177
+
178
+    /**
179
+     * Prepares an SQL statement.
180
+     *
181
+     * @param string $statement The SQL statement to prepare.
182
+     * @param int $limit
183
+     * @param int $offset
184
+     * @return \Doctrine\DBAL\Driver\Statement The prepared statement.
185
+     */
186
+    public function prepare($statement, $limit = null, $offset = null) {
187
+        if ($limit === -1) {
188
+            $limit = null;
189
+        }
190
+        if (!is_null($limit)) {
191
+            $platform = $this->getDatabasePlatform();
192
+            $statement = $platform->modifyLimitQuery($statement, $limit, $offset);
193
+        }
194
+        $statement = $this->replaceTablePrefix($statement);
195
+        $statement = $this->adapter->fixupStatement($statement);
196
+
197
+        return parent::prepare($statement);
198
+    }
199
+
200
+    /**
201
+     * Executes an, optionally parametrized, SQL query.
202
+     *
203
+     * If the query is parametrized, a prepared statement is used.
204
+     * If an SQLLogger is configured, the execution is logged.
205
+     *
206
+     * @param string                                      $sql  The SQL query to execute.
207
+     * @param array                                       $params The parameters to bind to the query, if any.
208
+     * @param array                                       $types  The types the previous parameters are in.
209
+     * @param \Doctrine\DBAL\Cache\QueryCacheProfile|null $qcp    The query cache profile, optional.
210
+     *
211
+     * @return \Doctrine\DBAL\Driver\Statement The executed statement.
212
+     *
213
+     * @throws \Doctrine\DBAL\DBALException
214
+     */
215
+    public function executeQuery($sql, array $params = [], $types = [], QueryCacheProfile $qcp = null) {
216
+        $sql = $this->replaceTablePrefix($sql);
217
+        $sql = $this->adapter->fixupStatement($sql);
218
+        $this->queriesExecuted++;
219
+        return parent::executeQuery($sql, $params, $types, $qcp);
220
+    }
221
+
222
+    public function executeUpdate($sql, array $params = [], array $types = []) {
223
+        $sql = $this->replaceTablePrefix($sql);
224
+        $sql = $this->adapter->fixupStatement($sql);
225
+        $this->queriesExecuted++;
226
+        return parent::executeUpdate($sql, $params, $types);
227
+    }
228
+
229
+    /**
230
+     * Executes an SQL INSERT/UPDATE/DELETE query with the given parameters
231
+     * and returns the number of affected rows.
232
+     *
233
+     * This method supports PDO binding types as well as DBAL mapping types.
234
+     *
235
+     * @param string $sql  The SQL query.
236
+     * @param array  $params The query parameters.
237
+     * @param array  $types  The parameter types.
238
+     *
239
+     * @return integer The number of affected rows.
240
+     *
241
+     * @throws \Doctrine\DBAL\DBALException
242
+     */
243
+    public function executeStatement($sql, array $params = [], array $types = []) {
244
+        $sql = $this->replaceTablePrefix($sql);
245
+        $sql = $this->adapter->fixupStatement($sql);
246
+        $this->queriesExecuted++;
247
+        return parent::executeStatement($sql, $params, $types);
248
+    }
249
+
250
+    /**
251
+     * Returns the ID of the last inserted row, or the last value from a sequence object,
252
+     * depending on the underlying driver.
253
+     *
254
+     * Note: This method may not return a meaningful or consistent result across different drivers,
255
+     * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY
256
+     * columns or sequences.
257
+     *
258
+     * @param string $seqName Name of the sequence object from which the ID should be returned.
259
+     * @return string A string representation of the last inserted ID.
260
+     */
261
+    public function lastInsertId($seqName = null) {
262
+        if ($seqName) {
263
+            $seqName = $this->replaceTablePrefix($seqName);
264
+        }
265
+        return $this->adapter->lastInsertId($seqName);
266
+    }
267
+
268
+    // internal use
269
+    public function realLastInsertId($seqName = null) {
270
+        return parent::lastInsertId($seqName);
271
+    }
272
+
273
+    /**
274
+     * Insert a row if the matching row does not exists. To accomplish proper race condition avoidance
275
+     * it is needed that there is also a unique constraint on the values. Then this method will
276
+     * catch the exception and return 0.
277
+     *
278
+     * @param string $table The table name (will replace *PREFIX* with the actual prefix)
279
+     * @param array $input data that should be inserted into the table  (column name => value)
280
+     * @param array|null $compare List of values that should be checked for "if not exists"
281
+     *				If this is null or an empty array, all keys of $input will be compared
282
+     *				Please note: text fields (clob) must not be used in the compare array
283
+     * @return int number of inserted rows
284
+     * @throws \Doctrine\DBAL\DBALException
285
+     * @deprecated 15.0.0 - use unique index and "try { $db->insert() } catch (UniqueConstraintViolationException $e) {}" instead, because it is more reliable and does not have the risk for deadlocks - see https://github.com/nextcloud/server/pull/12371
286
+     */
287
+    public function insertIfNotExist($table, $input, array $compare = null) {
288
+        return $this->adapter->insertIfNotExist($table, $input, $compare);
289
+    }
290
+
291
+    public function insertIgnoreConflict(string $table, array $values) : int {
292
+        return $this->adapter->insertIgnoreConflict($table, $values);
293
+    }
294
+
295
+    private function getType($value) {
296
+        if (is_bool($value)) {
297
+            return IQueryBuilder::PARAM_BOOL;
298
+        } elseif (is_int($value)) {
299
+            return IQueryBuilder::PARAM_INT;
300
+        } else {
301
+            return IQueryBuilder::PARAM_STR;
302
+        }
303
+    }
304
+
305
+    /**
306
+     * Insert or update a row value
307
+     *
308
+     * @param string $table
309
+     * @param array $keys (column name => value)
310
+     * @param array $values (column name => value)
311
+     * @param array $updatePreconditionValues ensure values match preconditions (column name => value)
312
+     * @return int number of new rows
313
+     * @throws \Doctrine\DBAL\DBALException
314
+     * @throws PreConditionNotMetException
315
+     */
316
+    public function setValues($table, array $keys, array $values, array $updatePreconditionValues = []) {
317
+        try {
318
+            $insertQb = $this->getQueryBuilder();
319
+            $insertQb->insert($table)
320
+                ->values(
321
+                    array_map(function ($value) use ($insertQb) {
322
+                        return $insertQb->createNamedParameter($value, $this->getType($value));
323
+                    }, array_merge($keys, $values))
324
+                );
325
+            return $insertQb->execute();
326
+        } catch (NotNullConstraintViolationException $e) {
327
+            throw $e;
328
+        } catch (ConstraintViolationException $e) {
329
+            // value already exists, try update
330
+            $updateQb = $this->getQueryBuilder();
331
+            $updateQb->update($table);
332
+            foreach ($values as $name => $value) {
333
+                $updateQb->set($name, $updateQb->createNamedParameter($value, $this->getType($value)));
334
+            }
335
+            $where = $updateQb->expr()->andX();
336
+            $whereValues = array_merge($keys, $updatePreconditionValues);
337
+            foreach ($whereValues as $name => $value) {
338
+                if ($value === '') {
339
+                    $where->add($updateQb->expr()->emptyString(
340
+                        $name
341
+                    ));
342
+                } else {
343
+                    $where->add($updateQb->expr()->eq(
344
+                        $name,
345
+                        $updateQb->createNamedParameter($value, $this->getType($value)),
346
+                        $this->getType($value)
347
+                    ));
348
+                }
349
+            }
350
+            $updateQb->where($where);
351
+            $affected = $updateQb->execute();
352
+
353
+            if ($affected === 0 && !empty($updatePreconditionValues)) {
354
+                throw new PreConditionNotMetException();
355
+            }
356
+
357
+            return 0;
358
+        }
359
+    }
360
+
361
+    /**
362
+     * Create an exclusive read+write lock on a table
363
+     *
364
+     * @param string $tableName
365
+     * @throws \BadMethodCallException When trying to acquire a second lock
366
+     * @since 9.1.0
367
+     */
368
+    public function lockTable($tableName) {
369
+        if ($this->lockedTable !== null) {
370
+            throw new \BadMethodCallException('Can not lock a new table until the previous lock is released.');
371
+        }
372
+
373
+        $tableName = $this->tablePrefix . $tableName;
374
+        $this->lockedTable = $tableName;
375
+        $this->adapter->lockTable($tableName);
376
+    }
377
+
378
+    /**
379
+     * Release a previous acquired lock again
380
+     *
381
+     * @since 9.1.0
382
+     */
383
+    public function unlockTable() {
384
+        $this->adapter->unlockTable();
385
+        $this->lockedTable = null;
386
+    }
387
+
388
+    /**
389
+     * returns the error code and message as a string for logging
390
+     * works with DoctrineException
391
+     * @return string
392
+     */
393
+    public function getError() {
394
+        $msg = $this->errorCode() . ': ';
395
+        $errorInfo = $this->errorInfo();
396
+        if (is_array($errorInfo)) {
397
+            $msg .= 'SQLSTATE = '.$errorInfo[0] . ', ';
398
+            $msg .= 'Driver Code = '.$errorInfo[1] . ', ';
399
+            $msg .= 'Driver Message = '.$errorInfo[2];
400
+        }
401
+        return $msg;
402
+    }
403
+
404
+    /**
405
+     * Drop a table from the database if it exists
406
+     *
407
+     * @param string $table table name without the prefix
408
+     */
409
+    public function dropTable($table) {
410
+        $table = $this->tablePrefix . trim($table);
411
+        $schema = $this->getSchemaManager();
412
+        if ($schema->tablesExist([$table])) {
413
+            $schema->dropTable($table);
414
+        }
415
+    }
416
+
417
+    /**
418
+     * Check if a table exists
419
+     *
420
+     * @param string $table table name without the prefix
421
+     * @return bool
422
+     */
423
+    public function tableExists($table) {
424
+        $table = $this->tablePrefix . trim($table);
425
+        $schema = $this->getSchemaManager();
426
+        return $schema->tablesExist([$table]);
427
+    }
428
+
429
+    // internal use
430
+    /**
431
+     * @param string $statement
432
+     * @return string
433
+     */
434
+    protected function replaceTablePrefix($statement) {
435
+        return str_replace('*PREFIX*', $this->tablePrefix, $statement);
436
+    }
437
+
438
+    /**
439
+     * Check if a transaction is active
440
+     *
441
+     * @return bool
442
+     * @since 8.2.0
443
+     */
444
+    public function inTransaction() {
445
+        return $this->getTransactionNestingLevel() > 0;
446
+    }
447
+
448
+    /**
449
+     * Escape a parameter to be used in a LIKE query
450
+     *
451
+     * @param string $param
452
+     * @return string
453
+     */
454
+    public function escapeLikeParameter($param) {
455
+        return addcslashes($param, '\\_%');
456
+    }
457
+
458
+    /**
459
+     * Check whether or not the current database support 4byte wide unicode
460
+     *
461
+     * @return bool
462
+     * @since 11.0.0
463
+     */
464
+    public function supports4ByteText() {
465
+        if (!$this->getDatabasePlatform() instanceof MySqlPlatform) {
466
+            return true;
467
+        }
468
+        return $this->getParams()['charset'] === 'utf8mb4';
469
+    }
470
+
471
+
472
+    /**
473
+     * Create the schema of the connected database
474
+     *
475
+     * @return Schema
476
+     */
477
+    public function createSchema() {
478
+        $schemaManager = new MDB2SchemaManager($this);
479
+        $migrator = $schemaManager->getMigrator();
480
+        return $migrator->createSchema();
481
+    }
482
+
483
+    /**
484
+     * Migrate the database to the given schema
485
+     *
486
+     * @param Schema $toSchema
487
+     */
488
+    public function migrateToSchema(Schema $toSchema) {
489
+        $schemaManager = new MDB2SchemaManager($this);
490
+        $migrator = $schemaManager->getMigrator();
491
+        $migrator->migrate($toSchema);
492
+    }
493 493
 }
Please login to merge, or discard this patch.
lib/private/DB/Migrator.php 2 patches
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -135,7 +135,7 @@  discard block
 block discarded – undo
135 135
 	 * @return string
136 136
 	 */
137 137
 	protected function generateTemporaryTableName($name) {
138
-		return $this->config->getSystemValue('dbtableprefix', 'oc_') . $name . '_' . $this->random->generate(13, ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS);
138
+		return $this->config->getSystemValue('dbtableprefix', 'oc_').$name.'_'.$this->random->generate(13, ISecureRandom::CHAR_LOWER.ISecureRandom::CHAR_DIGITS);
139 139
 	}
140 140
 
141 141
 	/**
@@ -186,7 +186,7 @@  discard block
 block discarded – undo
186 186
 				$indexName = $index->getName();
187 187
 			} else {
188 188
 				// avoid conflicts in index names
189
-				$indexName = $this->config->getSystemValue('dbtableprefix', 'oc_') . $this->random->generate(13, ISecureRandom::CHAR_LOWER);
189
+				$indexName = $this->config->getSystemValue('dbtableprefix', 'oc_').$this->random->generate(13, ISecureRandom::CHAR_LOWER);
190 190
 			}
191 191
 			$newIndexes[] = new Index($indexName, $index->getColumns(), $index->isUnique(), $index->isPrimary());
192 192
 		}
@@ -271,15 +271,15 @@  discard block
 block discarded – undo
271 271
 		$quotedSource = $this->connection->quoteIdentifier($sourceName);
272 272
 		$quotedTarget = $this->connection->quoteIdentifier($targetName);
273 273
 
274
-		$this->connection->exec('CREATE TABLE ' . $quotedTarget . ' (LIKE ' . $quotedSource . ')');
275
-		$this->connection->exec('INSERT INTO ' . $quotedTarget . ' SELECT * FROM ' . $quotedSource);
274
+		$this->connection->exec('CREATE TABLE '.$quotedTarget.' (LIKE '.$quotedSource.')');
275
+		$this->connection->exec('INSERT INTO '.$quotedTarget.' SELECT * FROM '.$quotedSource);
276 276
 	}
277 277
 
278 278
 	/**
279 279
 	 * @param string $name
280 280
 	 */
281 281
 	protected function dropTable($name) {
282
-		$this->connection->exec('DROP TABLE ' . $this->connection->quoteIdentifier($name));
282
+		$this->connection->exec('DROP TABLE '.$this->connection->quoteIdentifier($name));
283 283
 	}
284 284
 
285 285
 	/**
@@ -287,14 +287,14 @@  discard block
 block discarded – undo
287 287
 	 * @return string
288 288
 	 */
289 289
 	protected function convertStatementToScript($statement) {
290
-		$script = $statement . ';';
290
+		$script = $statement.';';
291 291
 		$script .= PHP_EOL;
292 292
 		$script .= PHP_EOL;
293 293
 		return $script;
294 294
 	}
295 295
 
296 296
 	protected function getFilterExpression() {
297
-		return '/^' . preg_quote($this->config->getSystemValue('dbtableprefix', 'oc_')) . '/';
297
+		return '/^'.preg_quote($this->config->getSystemValue('dbtableprefix', 'oc_')).'/';
298 298
 	}
299 299
 
300 300
 	protected function emit($sql, $step, $max) {
Please login to merge, or discard this patch.
Indentation   +267 added lines, -267 removed lines patch added patch discarded remove patch
@@ -46,271 +46,271 @@
 block discarded – undo
46 46
 
47 47
 class Migrator {
48 48
 
49
-	/** @var \Doctrine\DBAL\Connection */
50
-	protected $connection;
51
-
52
-	/** @var ISecureRandom */
53
-	private $random;
54
-
55
-	/** @var IConfig */
56
-	protected $config;
57
-
58
-	/** @var EventDispatcherInterface  */
59
-	private $dispatcher;
60
-
61
-	/** @var bool */
62
-	private $noEmit = false;
63
-
64
-	/**
65
-	 * @param \Doctrine\DBAL\Connection $connection
66
-	 * @param ISecureRandom $random
67
-	 * @param IConfig $config
68
-	 * @param EventDispatcherInterface $dispatcher
69
-	 */
70
-	public function __construct(\Doctrine\DBAL\Connection $connection,
71
-								ISecureRandom $random,
72
-								IConfig $config,
73
-								EventDispatcherInterface $dispatcher = null) {
74
-		$this->connection = $connection;
75
-		$this->random = $random;
76
-		$this->config = $config;
77
-		$this->dispatcher = $dispatcher;
78
-	}
79
-
80
-	/**
81
-	 * @param \Doctrine\DBAL\Schema\Schema $targetSchema
82
-	 */
83
-	public function migrate(Schema $targetSchema) {
84
-		$this->noEmit = true;
85
-		$this->applySchema($targetSchema);
86
-	}
87
-
88
-	/**
89
-	 * @param \Doctrine\DBAL\Schema\Schema $targetSchema
90
-	 * @return string
91
-	 */
92
-	public function generateChangeScript(Schema $targetSchema) {
93
-		$schemaDiff = $this->getDiff($targetSchema, $this->connection);
94
-
95
-		$script = '';
96
-		$sqls = $schemaDiff->toSql($this->connection->getDatabasePlatform());
97
-		foreach ($sqls as $sql) {
98
-			$script .= $this->convertStatementToScript($sql);
99
-		}
100
-
101
-		return $script;
102
-	}
103
-
104
-	/**
105
-	 * @param Schema $targetSchema
106
-	 * @throws \OC\DB\MigrationException
107
-	 */
108
-	public function checkMigrate(Schema $targetSchema) {
109
-		$this->noEmit = true;
110
-		/**@var \Doctrine\DBAL\Schema\Table[] $tables */
111
-		$tables = $targetSchema->getTables();
112
-		$filterExpression = $this->getFilterExpression();
113
-		$this->connection->getConfiguration()->
114
-			setFilterSchemaAssetsExpression($filterExpression);
115
-		$existingTables = $this->connection->getSchemaManager()->listTableNames();
116
-
117
-		$step = 0;
118
-		foreach ($tables as $table) {
119
-			if (strpos($table->getName(), '.')) {
120
-				list(, $tableName) = explode('.', $table->getName());
121
-			} else {
122
-				$tableName = $table->getName();
123
-			}
124
-			$this->emitCheckStep($tableName, $step++, count($tables));
125
-			// don't need to check for new tables
126
-			if (array_search($tableName, $existingTables) !== false) {
127
-				$this->checkTableMigrate($table);
128
-			}
129
-		}
130
-	}
131
-
132
-	/**
133
-	 * Create a unique name for the temporary table
134
-	 *
135
-	 * @param string $name
136
-	 * @return string
137
-	 */
138
-	protected function generateTemporaryTableName($name) {
139
-		return $this->config->getSystemValue('dbtableprefix', 'oc_') . $name . '_' . $this->random->generate(13, ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS);
140
-	}
141
-
142
-	/**
143
-	 * Check the migration of a table on a copy so we can detect errors before messing with the real table
144
-	 *
145
-	 * @param \Doctrine\DBAL\Schema\Table $table
146
-	 * @throws \OC\DB\MigrationException
147
-	 */
148
-	protected function checkTableMigrate(Table $table) {
149
-		$name = $table->getName();
150
-		$tmpName = $this->generateTemporaryTableName($name);
151
-
152
-		$this->copyTable($name, $tmpName);
153
-
154
-		//create the migration schema for the temporary table
155
-		$tmpTable = $this->renameTableSchema($table, $tmpName);
156
-		$schemaConfig = new SchemaConfig();
157
-		$schemaConfig->setName($this->connection->getDatabase());
158
-		$schema = new Schema([$tmpTable], [], $schemaConfig);
159
-
160
-		try {
161
-			$this->applySchema($schema);
162
-			$this->dropTable($tmpName);
163
-		} catch (DBALException $e) {
164
-			// pgsql needs to commit it's failed transaction before doing anything else
165
-			if ($this->connection->isTransactionActive()) {
166
-				$this->connection->commit();
167
-			}
168
-			$this->dropTable($tmpName);
169
-			throw new MigrationException($table->getName(), $e->getMessage());
170
-		}
171
-	}
172
-
173
-	/**
174
-	 * @param \Doctrine\DBAL\Schema\Table $table
175
-	 * @param string $newName
176
-	 * @return \Doctrine\DBAL\Schema\Table
177
-	 */
178
-	protected function renameTableSchema(Table $table, $newName) {
179
-		/**
180
-		 * @var \Doctrine\DBAL\Schema\Index[] $indexes
181
-		 */
182
-		$indexes = $table->getIndexes();
183
-		$newIndexes = [];
184
-		foreach ($indexes as $index) {
185
-			if ($index->isPrimary()) {
186
-				// do not rename primary key
187
-				$indexName = $index->getName();
188
-			} else {
189
-				// avoid conflicts in index names
190
-				$indexName = $this->config->getSystemValue('dbtableprefix', 'oc_') . $this->random->generate(13, ISecureRandom::CHAR_LOWER);
191
-			}
192
-			$newIndexes[] = new Index($indexName, $index->getColumns(), $index->isUnique(), $index->isPrimary());
193
-		}
194
-
195
-		// foreign keys are not supported so we just set it to an empty array
196
-		return new Table($newName, $table->getColumns(), $newIndexes, [], 0, $table->getOptions());
197
-	}
198
-
199
-	public function createSchema() {
200
-		$filterExpression = $this->getFilterExpression();
201
-		$this->connection->getConfiguration()->setFilterSchemaAssetsExpression($filterExpression);
202
-		return $this->connection->getSchemaManager()->createSchema();
203
-	}
204
-
205
-	/**
206
-	 * @param Schema $targetSchema
207
-	 * @param \Doctrine\DBAL\Connection $connection
208
-	 * @return \Doctrine\DBAL\Schema\SchemaDiff
209
-	 * @throws DBALException
210
-	 */
211
-	protected function getDiff(Schema $targetSchema, \Doctrine\DBAL\Connection $connection) {
212
-		// adjust varchar columns with a length higher then getVarcharMaxLength to clob
213
-		foreach ($targetSchema->getTables() as $table) {
214
-			foreach ($table->getColumns() as $column) {
215
-				if ($column->getType() instanceof StringType) {
216
-					if ($column->getLength() > $connection->getDatabasePlatform()->getVarcharMaxLength()) {
217
-						$column->setType(Type::getType('text'));
218
-						$column->setLength(null);
219
-					}
220
-				}
221
-			}
222
-		}
223
-
224
-		$filterExpression = $this->getFilterExpression();
225
-		$this->connection->getConfiguration()->setFilterSchemaAssetsExpression($filterExpression);
226
-		$sourceSchema = $connection->getSchemaManager()->createSchema();
227
-
228
-		// remove tables we don't know about
229
-		foreach ($sourceSchema->getTables() as $table) {
230
-			if (!$targetSchema->hasTable($table->getName())) {
231
-				$sourceSchema->dropTable($table->getName());
232
-			}
233
-		}
234
-		// remove sequences we don't know about
235
-		foreach ($sourceSchema->getSequences() as $table) {
236
-			if (!$targetSchema->hasSequence($table->getName())) {
237
-				$sourceSchema->dropSequence($table->getName());
238
-			}
239
-		}
240
-
241
-		$comparator = new Comparator();
242
-		return $comparator->compare($sourceSchema, $targetSchema);
243
-	}
244
-
245
-	/**
246
-	 * @param \Doctrine\DBAL\Schema\Schema $targetSchema
247
-	 * @param \Doctrine\DBAL\Connection $connection
248
-	 */
249
-	protected function applySchema(Schema $targetSchema, \Doctrine\DBAL\Connection $connection = null) {
250
-		if (is_null($connection)) {
251
-			$connection = $this->connection;
252
-		}
253
-
254
-		$schemaDiff = $this->getDiff($targetSchema, $connection);
255
-
256
-		$connection->beginTransaction();
257
-		$sqls = $schemaDiff->toSql($connection->getDatabasePlatform());
258
-		$step = 0;
259
-		foreach ($sqls as $sql) {
260
-			$this->emit($sql, $step++, count($sqls));
261
-			$connection->query($sql);
262
-		}
263
-		$connection->commit();
264
-	}
265
-
266
-	/**
267
-	 * @param string $sourceName
268
-	 * @param string $targetName
269
-	 */
270
-	protected function copyTable($sourceName, $targetName) {
271
-		$quotedSource = $this->connection->quoteIdentifier($sourceName);
272
-		$quotedTarget = $this->connection->quoteIdentifier($targetName);
273
-
274
-		$this->connection->exec('CREATE TABLE ' . $quotedTarget . ' (LIKE ' . $quotedSource . ')');
275
-		$this->connection->exec('INSERT INTO ' . $quotedTarget . ' SELECT * FROM ' . $quotedSource);
276
-	}
277
-
278
-	/**
279
-	 * @param string $name
280
-	 */
281
-	protected function dropTable($name) {
282
-		$this->connection->exec('DROP TABLE ' . $this->connection->quoteIdentifier($name));
283
-	}
284
-
285
-	/**
286
-	 * @param $statement
287
-	 * @return string
288
-	 */
289
-	protected function convertStatementToScript($statement) {
290
-		$script = $statement . ';';
291
-		$script .= PHP_EOL;
292
-		$script .= PHP_EOL;
293
-		return $script;
294
-	}
295
-
296
-	protected function getFilterExpression() {
297
-		return '/^' . preg_quote($this->config->getSystemValue('dbtableprefix', 'oc_')) . '/';
298
-	}
299
-
300
-	protected function emit($sql, $step, $max) {
301
-		if ($this->noEmit) {
302
-			return;
303
-		}
304
-		if (is_null($this->dispatcher)) {
305
-			return;
306
-		}
307
-		$this->dispatcher->dispatch('\OC\DB\Migrator::executeSql', new GenericEvent($sql, [$step + 1, $max]));
308
-	}
309
-
310
-	private function emitCheckStep($tableName, $step, $max) {
311
-		if (is_null($this->dispatcher)) {
312
-			return;
313
-		}
314
-		$this->dispatcher->dispatch('\OC\DB\Migrator::checkTable', new GenericEvent($tableName, [$step + 1, $max]));
315
-	}
49
+    /** @var \Doctrine\DBAL\Connection */
50
+    protected $connection;
51
+
52
+    /** @var ISecureRandom */
53
+    private $random;
54
+
55
+    /** @var IConfig */
56
+    protected $config;
57
+
58
+    /** @var EventDispatcherInterface  */
59
+    private $dispatcher;
60
+
61
+    /** @var bool */
62
+    private $noEmit = false;
63
+
64
+    /**
65
+     * @param \Doctrine\DBAL\Connection $connection
66
+     * @param ISecureRandom $random
67
+     * @param IConfig $config
68
+     * @param EventDispatcherInterface $dispatcher
69
+     */
70
+    public function __construct(\Doctrine\DBAL\Connection $connection,
71
+                                ISecureRandom $random,
72
+                                IConfig $config,
73
+                                EventDispatcherInterface $dispatcher = null) {
74
+        $this->connection = $connection;
75
+        $this->random = $random;
76
+        $this->config = $config;
77
+        $this->dispatcher = $dispatcher;
78
+    }
79
+
80
+    /**
81
+     * @param \Doctrine\DBAL\Schema\Schema $targetSchema
82
+     */
83
+    public function migrate(Schema $targetSchema) {
84
+        $this->noEmit = true;
85
+        $this->applySchema($targetSchema);
86
+    }
87
+
88
+    /**
89
+     * @param \Doctrine\DBAL\Schema\Schema $targetSchema
90
+     * @return string
91
+     */
92
+    public function generateChangeScript(Schema $targetSchema) {
93
+        $schemaDiff = $this->getDiff($targetSchema, $this->connection);
94
+
95
+        $script = '';
96
+        $sqls = $schemaDiff->toSql($this->connection->getDatabasePlatform());
97
+        foreach ($sqls as $sql) {
98
+            $script .= $this->convertStatementToScript($sql);
99
+        }
100
+
101
+        return $script;
102
+    }
103
+
104
+    /**
105
+     * @param Schema $targetSchema
106
+     * @throws \OC\DB\MigrationException
107
+     */
108
+    public function checkMigrate(Schema $targetSchema) {
109
+        $this->noEmit = true;
110
+        /**@var \Doctrine\DBAL\Schema\Table[] $tables */
111
+        $tables = $targetSchema->getTables();
112
+        $filterExpression = $this->getFilterExpression();
113
+        $this->connection->getConfiguration()->
114
+            setFilterSchemaAssetsExpression($filterExpression);
115
+        $existingTables = $this->connection->getSchemaManager()->listTableNames();
116
+
117
+        $step = 0;
118
+        foreach ($tables as $table) {
119
+            if (strpos($table->getName(), '.')) {
120
+                list(, $tableName) = explode('.', $table->getName());
121
+            } else {
122
+                $tableName = $table->getName();
123
+            }
124
+            $this->emitCheckStep($tableName, $step++, count($tables));
125
+            // don't need to check for new tables
126
+            if (array_search($tableName, $existingTables) !== false) {
127
+                $this->checkTableMigrate($table);
128
+            }
129
+        }
130
+    }
131
+
132
+    /**
133
+     * Create a unique name for the temporary table
134
+     *
135
+     * @param string $name
136
+     * @return string
137
+     */
138
+    protected function generateTemporaryTableName($name) {
139
+        return $this->config->getSystemValue('dbtableprefix', 'oc_') . $name . '_' . $this->random->generate(13, ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS);
140
+    }
141
+
142
+    /**
143
+     * Check the migration of a table on a copy so we can detect errors before messing with the real table
144
+     *
145
+     * @param \Doctrine\DBAL\Schema\Table $table
146
+     * @throws \OC\DB\MigrationException
147
+     */
148
+    protected function checkTableMigrate(Table $table) {
149
+        $name = $table->getName();
150
+        $tmpName = $this->generateTemporaryTableName($name);
151
+
152
+        $this->copyTable($name, $tmpName);
153
+
154
+        //create the migration schema for the temporary table
155
+        $tmpTable = $this->renameTableSchema($table, $tmpName);
156
+        $schemaConfig = new SchemaConfig();
157
+        $schemaConfig->setName($this->connection->getDatabase());
158
+        $schema = new Schema([$tmpTable], [], $schemaConfig);
159
+
160
+        try {
161
+            $this->applySchema($schema);
162
+            $this->dropTable($tmpName);
163
+        } catch (DBALException $e) {
164
+            // pgsql needs to commit it's failed transaction before doing anything else
165
+            if ($this->connection->isTransactionActive()) {
166
+                $this->connection->commit();
167
+            }
168
+            $this->dropTable($tmpName);
169
+            throw new MigrationException($table->getName(), $e->getMessage());
170
+        }
171
+    }
172
+
173
+    /**
174
+     * @param \Doctrine\DBAL\Schema\Table $table
175
+     * @param string $newName
176
+     * @return \Doctrine\DBAL\Schema\Table
177
+     */
178
+    protected function renameTableSchema(Table $table, $newName) {
179
+        /**
180
+         * @var \Doctrine\DBAL\Schema\Index[] $indexes
181
+         */
182
+        $indexes = $table->getIndexes();
183
+        $newIndexes = [];
184
+        foreach ($indexes as $index) {
185
+            if ($index->isPrimary()) {
186
+                // do not rename primary key
187
+                $indexName = $index->getName();
188
+            } else {
189
+                // avoid conflicts in index names
190
+                $indexName = $this->config->getSystemValue('dbtableprefix', 'oc_') . $this->random->generate(13, ISecureRandom::CHAR_LOWER);
191
+            }
192
+            $newIndexes[] = new Index($indexName, $index->getColumns(), $index->isUnique(), $index->isPrimary());
193
+        }
194
+
195
+        // foreign keys are not supported so we just set it to an empty array
196
+        return new Table($newName, $table->getColumns(), $newIndexes, [], 0, $table->getOptions());
197
+    }
198
+
199
+    public function createSchema() {
200
+        $filterExpression = $this->getFilterExpression();
201
+        $this->connection->getConfiguration()->setFilterSchemaAssetsExpression($filterExpression);
202
+        return $this->connection->getSchemaManager()->createSchema();
203
+    }
204
+
205
+    /**
206
+     * @param Schema $targetSchema
207
+     * @param \Doctrine\DBAL\Connection $connection
208
+     * @return \Doctrine\DBAL\Schema\SchemaDiff
209
+     * @throws DBALException
210
+     */
211
+    protected function getDiff(Schema $targetSchema, \Doctrine\DBAL\Connection $connection) {
212
+        // adjust varchar columns with a length higher then getVarcharMaxLength to clob
213
+        foreach ($targetSchema->getTables() as $table) {
214
+            foreach ($table->getColumns() as $column) {
215
+                if ($column->getType() instanceof StringType) {
216
+                    if ($column->getLength() > $connection->getDatabasePlatform()->getVarcharMaxLength()) {
217
+                        $column->setType(Type::getType('text'));
218
+                        $column->setLength(null);
219
+                    }
220
+                }
221
+            }
222
+        }
223
+
224
+        $filterExpression = $this->getFilterExpression();
225
+        $this->connection->getConfiguration()->setFilterSchemaAssetsExpression($filterExpression);
226
+        $sourceSchema = $connection->getSchemaManager()->createSchema();
227
+
228
+        // remove tables we don't know about
229
+        foreach ($sourceSchema->getTables() as $table) {
230
+            if (!$targetSchema->hasTable($table->getName())) {
231
+                $sourceSchema->dropTable($table->getName());
232
+            }
233
+        }
234
+        // remove sequences we don't know about
235
+        foreach ($sourceSchema->getSequences() as $table) {
236
+            if (!$targetSchema->hasSequence($table->getName())) {
237
+                $sourceSchema->dropSequence($table->getName());
238
+            }
239
+        }
240
+
241
+        $comparator = new Comparator();
242
+        return $comparator->compare($sourceSchema, $targetSchema);
243
+    }
244
+
245
+    /**
246
+     * @param \Doctrine\DBAL\Schema\Schema $targetSchema
247
+     * @param \Doctrine\DBAL\Connection $connection
248
+     */
249
+    protected function applySchema(Schema $targetSchema, \Doctrine\DBAL\Connection $connection = null) {
250
+        if (is_null($connection)) {
251
+            $connection = $this->connection;
252
+        }
253
+
254
+        $schemaDiff = $this->getDiff($targetSchema, $connection);
255
+
256
+        $connection->beginTransaction();
257
+        $sqls = $schemaDiff->toSql($connection->getDatabasePlatform());
258
+        $step = 0;
259
+        foreach ($sqls as $sql) {
260
+            $this->emit($sql, $step++, count($sqls));
261
+            $connection->query($sql);
262
+        }
263
+        $connection->commit();
264
+    }
265
+
266
+    /**
267
+     * @param string $sourceName
268
+     * @param string $targetName
269
+     */
270
+    protected function copyTable($sourceName, $targetName) {
271
+        $quotedSource = $this->connection->quoteIdentifier($sourceName);
272
+        $quotedTarget = $this->connection->quoteIdentifier($targetName);
273
+
274
+        $this->connection->exec('CREATE TABLE ' . $quotedTarget . ' (LIKE ' . $quotedSource . ')');
275
+        $this->connection->exec('INSERT INTO ' . $quotedTarget . ' SELECT * FROM ' . $quotedSource);
276
+    }
277
+
278
+    /**
279
+     * @param string $name
280
+     */
281
+    protected function dropTable($name) {
282
+        $this->connection->exec('DROP TABLE ' . $this->connection->quoteIdentifier($name));
283
+    }
284
+
285
+    /**
286
+     * @param $statement
287
+     * @return string
288
+     */
289
+    protected function convertStatementToScript($statement) {
290
+        $script = $statement . ';';
291
+        $script .= PHP_EOL;
292
+        $script .= PHP_EOL;
293
+        return $script;
294
+    }
295
+
296
+    protected function getFilterExpression() {
297
+        return '/^' . preg_quote($this->config->getSystemValue('dbtableprefix', 'oc_')) . '/';
298
+    }
299
+
300
+    protected function emit($sql, $step, $max) {
301
+        if ($this->noEmit) {
302
+            return;
303
+        }
304
+        if (is_null($this->dispatcher)) {
305
+            return;
306
+        }
307
+        $this->dispatcher->dispatch('\OC\DB\Migrator::executeSql', new GenericEvent($sql, [$step + 1, $max]));
308
+    }
309
+
310
+    private function emitCheckStep($tableName, $step, $max) {
311
+        if (is_null($this->dispatcher)) {
312
+            return;
313
+        }
314
+        $this->dispatcher->dispatch('\OC\DB\Migrator::checkTable', new GenericEvent($tableName, [$step + 1, $max]));
315
+    }
316 316
 }
Please login to merge, or discard this patch.
lib/private/DB/MDB2SchemaWriter.php 2 patches
Indentation   +138 added lines, -138 removed lines patch added patch discarded remove patch
@@ -31,150 +31,150 @@
 block discarded – undo
31 31
 
32 32
 class MDB2SchemaWriter {
33 33
 
34
-	/**
35
-	 * @param string $file
36
-	 * @param \OC\DB\Connection $conn
37
-	 * @return bool
38
-	 */
39
-	public static function saveSchemaToFile($file, \OC\DB\Connection $conn) {
40
-		$config = \OC::$server->getConfig();
34
+    /**
35
+     * @param string $file
36
+     * @param \OC\DB\Connection $conn
37
+     * @return bool
38
+     */
39
+    public static function saveSchemaToFile($file, \OC\DB\Connection $conn) {
40
+        $config = \OC::$server->getConfig();
41 41
 
42
-		$xml = new \SimpleXMLElement('<database/>');
43
-		$xml->addChild('name', $config->getSystemValue('dbname', 'owncloud'));
44
-		$xml->addChild('create', 'true');
45
-		$xml->addChild('overwrite', 'false');
46
-		if ($config->getSystemValue('dbtype', 'sqlite') === 'mysql' && $config->getSystemValue('mysql.utf8mb4', false)) {
47
-			$xml->addChild('charset', 'utf8mb4');
48
-		} else {
49
-			$xml->addChild('charset', 'utf8');
50
-		}
42
+        $xml = new \SimpleXMLElement('<database/>');
43
+        $xml->addChild('name', $config->getSystemValue('dbname', 'owncloud'));
44
+        $xml->addChild('create', 'true');
45
+        $xml->addChild('overwrite', 'false');
46
+        if ($config->getSystemValue('dbtype', 'sqlite') === 'mysql' && $config->getSystemValue('mysql.utf8mb4', false)) {
47
+            $xml->addChild('charset', 'utf8mb4');
48
+        } else {
49
+            $xml->addChild('charset', 'utf8');
50
+        }
51 51
 
52
-		// FIX ME: bloody work around
53
-		if ($config->getSystemValue('dbtype', 'sqlite') === 'oci') {
54
-			$filterExpression = '/^"' . preg_quote($conn->getPrefix()) . '/';
55
-		} else {
56
-			$filterExpression = '/^' . preg_quote($conn->getPrefix()) . '/';
57
-		}
58
-		$conn->getConfiguration()->setFilterSchemaAssetsExpression($filterExpression);
52
+        // FIX ME: bloody work around
53
+        if ($config->getSystemValue('dbtype', 'sqlite') === 'oci') {
54
+            $filterExpression = '/^"' . preg_quote($conn->getPrefix()) . '/';
55
+        } else {
56
+            $filterExpression = '/^' . preg_quote($conn->getPrefix()) . '/';
57
+        }
58
+        $conn->getConfiguration()->setFilterSchemaAssetsExpression($filterExpression);
59 59
 
60
-		foreach ($conn->getSchemaManager()->listTables() as $table) {
61
-			self::saveTable($table, $xml->addChild('table'));
62
-		}
63
-		file_put_contents($file, $xml->asXML());
64
-		return true;
65
-	}
60
+        foreach ($conn->getSchemaManager()->listTables() as $table) {
61
+            self::saveTable($table, $xml->addChild('table'));
62
+        }
63
+        file_put_contents($file, $xml->asXML());
64
+        return true;
65
+    }
66 66
 
67
-	/**
68
-	 * @param \Doctrine\DBAL\Schema\Table $table
69
-	 * @param \SimpleXMLElement $xml
70
-	 */
71
-	private static function saveTable($table, $xml) {
72
-		$xml->addChild('name', $table->getName());
73
-		$declaration = $xml->addChild('declaration');
74
-		foreach ($table->getColumns() as $column) {
75
-			self::saveColumn($column, $declaration->addChild('field'));
76
-		}
77
-		foreach ($table->getIndexes() as $index) {
78
-			if ($index->getName() == 'PRIMARY') {
79
-				$autoincrement = false;
80
-				foreach ($index->getColumns() as $column) {
81
-					if ($table->getColumn($column)->getAutoincrement()) {
82
-						$autoincrement = true;
83
-					}
84
-				}
85
-				if ($autoincrement) {
86
-					continue;
87
-				}
88
-			}
89
-			self::saveIndex($index, $declaration->addChild('index'));
90
-		}
91
-	}
67
+    /**
68
+     * @param \Doctrine\DBAL\Schema\Table $table
69
+     * @param \SimpleXMLElement $xml
70
+     */
71
+    private static function saveTable($table, $xml) {
72
+        $xml->addChild('name', $table->getName());
73
+        $declaration = $xml->addChild('declaration');
74
+        foreach ($table->getColumns() as $column) {
75
+            self::saveColumn($column, $declaration->addChild('field'));
76
+        }
77
+        foreach ($table->getIndexes() as $index) {
78
+            if ($index->getName() == 'PRIMARY') {
79
+                $autoincrement = false;
80
+                foreach ($index->getColumns() as $column) {
81
+                    if ($table->getColumn($column)->getAutoincrement()) {
82
+                        $autoincrement = true;
83
+                    }
84
+                }
85
+                if ($autoincrement) {
86
+                    continue;
87
+                }
88
+            }
89
+            self::saveIndex($index, $declaration->addChild('index'));
90
+        }
91
+    }
92 92
 
93
-	/**
94
-	 * @param Column $column
95
-	 * @param \SimpleXMLElement $xml
96
-	 */
97
-	private static function saveColumn($column, $xml) {
98
-		$xml->addChild('name', $column->getName());
99
-		switch ($column->getType()) {
100
-			case 'SmallInt':
101
-			case 'Integer':
102
-			case 'BigInt':
103
-				$xml->addChild('type', 'integer');
104
-				$default = $column->getDefault();
105
-				if (is_null($default) && $column->getAutoincrement()) {
106
-					$default = '0';
107
-				}
108
-				$xml->addChild('default', $default);
109
-				$xml->addChild('notnull', self::toBool($column->getNotnull()));
110
-				if ($column->getAutoincrement()) {
111
-					$xml->addChild('autoincrement', '1');
112
-				}
113
-				if ($column->getUnsigned()) {
114
-					$xml->addChild('unsigned', 'true');
115
-				}
116
-				$length = '4';
117
-				if ($column->getType() == 'SmallInt') {
118
-					$length = '2';
119
-				} elseif ($column->getType() == 'BigInt') {
120
-					$length = '8';
121
-				}
122
-				$xml->addChild('length', $length);
123
-				break;
124
-			case 'String':
125
-				$xml->addChild('type', 'text');
126
-				$default = trim($column->getDefault());
127
-				if ($default === '') {
128
-					$default = false;
129
-				}
130
-				$xml->addChild('default', $default);
131
-				$xml->addChild('notnull', self::toBool($column->getNotnull()));
132
-				$xml->addChild('length', $column->getLength());
133
-				break;
134
-			case 'Text':
135
-				$xml->addChild('type', 'clob');
136
-				$xml->addChild('notnull', self::toBool($column->getNotnull()));
137
-				break;
138
-			case 'Decimal':
139
-				$xml->addChild('type', 'decimal');
140
-				$xml->addChild('default', $column->getDefault());
141
-				$xml->addChild('notnull', self::toBool($column->getNotnull()));
142
-				$xml->addChild('length', '15');
143
-				break;
144
-			case 'Boolean':
145
-				$xml->addChild('type', 'integer');
146
-				$xml->addChild('default', $column->getDefault());
147
-				$xml->addChild('notnull', self::toBool($column->getNotnull()));
148
-				$xml->addChild('length', '1');
149
-				break;
150
-			case 'DateTime':
151
-				$xml->addChild('type', 'timestamp');
152
-				$xml->addChild('default', $column->getDefault());
153
-				$xml->addChild('notnull', self::toBool($column->getNotnull()));
154
-				break;
93
+    /**
94
+     * @param Column $column
95
+     * @param \SimpleXMLElement $xml
96
+     */
97
+    private static function saveColumn($column, $xml) {
98
+        $xml->addChild('name', $column->getName());
99
+        switch ($column->getType()) {
100
+            case 'SmallInt':
101
+            case 'Integer':
102
+            case 'BigInt':
103
+                $xml->addChild('type', 'integer');
104
+                $default = $column->getDefault();
105
+                if (is_null($default) && $column->getAutoincrement()) {
106
+                    $default = '0';
107
+                }
108
+                $xml->addChild('default', $default);
109
+                $xml->addChild('notnull', self::toBool($column->getNotnull()));
110
+                if ($column->getAutoincrement()) {
111
+                    $xml->addChild('autoincrement', '1');
112
+                }
113
+                if ($column->getUnsigned()) {
114
+                    $xml->addChild('unsigned', 'true');
115
+                }
116
+                $length = '4';
117
+                if ($column->getType() == 'SmallInt') {
118
+                    $length = '2';
119
+                } elseif ($column->getType() == 'BigInt') {
120
+                    $length = '8';
121
+                }
122
+                $xml->addChild('length', $length);
123
+                break;
124
+            case 'String':
125
+                $xml->addChild('type', 'text');
126
+                $default = trim($column->getDefault());
127
+                if ($default === '') {
128
+                    $default = false;
129
+                }
130
+                $xml->addChild('default', $default);
131
+                $xml->addChild('notnull', self::toBool($column->getNotnull()));
132
+                $xml->addChild('length', $column->getLength());
133
+                break;
134
+            case 'Text':
135
+                $xml->addChild('type', 'clob');
136
+                $xml->addChild('notnull', self::toBool($column->getNotnull()));
137
+                break;
138
+            case 'Decimal':
139
+                $xml->addChild('type', 'decimal');
140
+                $xml->addChild('default', $column->getDefault());
141
+                $xml->addChild('notnull', self::toBool($column->getNotnull()));
142
+                $xml->addChild('length', '15');
143
+                break;
144
+            case 'Boolean':
145
+                $xml->addChild('type', 'integer');
146
+                $xml->addChild('default', $column->getDefault());
147
+                $xml->addChild('notnull', self::toBool($column->getNotnull()));
148
+                $xml->addChild('length', '1');
149
+                break;
150
+            case 'DateTime':
151
+                $xml->addChild('type', 'timestamp');
152
+                $xml->addChild('default', $column->getDefault());
153
+                $xml->addChild('notnull', self::toBool($column->getNotnull()));
154
+                break;
155 155
 
156
-		}
157
-	}
156
+        }
157
+    }
158 158
 
159
-	/**
160
-	 * @param Index $index
161
-	 * @param \SimpleXMLElement $xml
162
-	 */
163
-	private static function saveIndex($index, $xml) {
164
-		$xml->addChild('name', $index->getName());
165
-		if ($index->isPrimary()) {
166
-			$xml->addChild('primary', 'true');
167
-		} elseif ($index->isUnique()) {
168
-			$xml->addChild('unique', 'true');
169
-		}
170
-		foreach ($index->getColumns() as $column) {
171
-			$field = $xml->addChild('field');
172
-			$field->addChild('name', $column);
173
-			$field->addChild('sorting', 'ascending');
174
-		}
175
-	}
159
+    /**
160
+     * @param Index $index
161
+     * @param \SimpleXMLElement $xml
162
+     */
163
+    private static function saveIndex($index, $xml) {
164
+        $xml->addChild('name', $index->getName());
165
+        if ($index->isPrimary()) {
166
+            $xml->addChild('primary', 'true');
167
+        } elseif ($index->isUnique()) {
168
+            $xml->addChild('unique', 'true');
169
+        }
170
+        foreach ($index->getColumns() as $column) {
171
+            $field = $xml->addChild('field');
172
+            $field->addChild('name', $column);
173
+            $field->addChild('sorting', 'ascending');
174
+        }
175
+    }
176 176
 
177
-	private static function toBool($bool) {
178
-		return $bool ? 'true' : 'false';
179
-	}
177
+    private static function toBool($bool) {
178
+        return $bool ? 'true' : 'false';
179
+    }
180 180
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -51,9 +51,9 @@
 block discarded – undo
51 51
 
52 52
 		// FIX ME: bloody work around
53 53
 		if ($config->getSystemValue('dbtype', 'sqlite') === 'oci') {
54
-			$filterExpression = '/^"' . preg_quote($conn->getPrefix()) . '/';
54
+			$filterExpression = '/^"'.preg_quote($conn->getPrefix()).'/';
55 55
 		} else {
56
-			$filterExpression = '/^' . preg_quote($conn->getPrefix()) . '/';
56
+			$filterExpression = '/^'.preg_quote($conn->getPrefix()).'/';
57 57
 		}
58 58
 		$conn->getConfiguration()->setFilterSchemaAssetsExpression($filterExpression);
59 59
 
Please login to merge, or discard this patch.