Passed
Push — master ( 509b8c...0b1212 )
by Richard
01:44
created

MysqlAdapter::tryAlteringColumn()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 4
c 0
b 0
f 0
nc 3
nop 3
dl 0
loc 6
rs 9.4285
1
<?php
2
namespace Maphper\DataSource;
3
class MysqlAdapter implements DatabaseAdapter {
4
	private $pdo;
5
	private $stmtCache;
6
    private $generalEditor;
7
8
	public function __construct(\PDO $pdo) {
9
		$this->pdo = $pdo;
10
		//Set to strict mode to detect 'out of range' errors, action at a distance but it needs to be set for all INSERT queries
11
		$this->pdo->query('SET sql_mode = STRICT_ALL_TABLES');
12
        $this->stmtCache = new StmtCache($pdo);
13
        $this->generalEditor = new GeneralEditDatabase($this->pdo, ['short_string_max_len' => 191]);
14
	}
15
16
	public function quote($str) {
17
		return $this->generalEditor->quote($str);
18
	}
19
20
	public function query(\Maphper\Lib\Query $query) {
21
		$stmt = $this->stmtCache->getCachedStmt($query->getSql());
22
		$args = $query->getArgs();
23
        $stmt->execute($args);
24
25
		return $stmt;
26
	}
27
28
    private function alterColumns($table, array $primaryKey, $data) {
29
        foreach ($data as $key => $value) {
30
			if ($this->generalEditor->isNotSavableType($value, $key, $primaryKey)) continue;
31
            
32
			$type = $this->generalEditor->getType($value);
33
			$this->tryAlteringColumn($table, $key, $type);
34
		}
35
    }
36
37
    private function tryAlteringColumn($table, $key, $type) {
38
        try {
39
            if (!$this->pdo->query('ALTER TABLE ' . $table . ' ADD ' . $this->quote($key) . ' ' . $type)) throw new \Exception('Could not alter table');
40
        }
41
        catch (\Exception $e) {
42
            $this->pdo->query('ALTER TABLE ' . $table . ' MODIFY ' . $this->quote($key) . ' ' . $type);
43
        }
44
    }
45
46
	public function alterDatabase($table, array $primaryKey, $data) {
47
		$this->generalEditor->createTable($table, $primaryKey, $data);
48
        $this->alterColumns($table, $primaryKey, $data);
49
	}
50
51
	public function lastInsertId() {
52
		return $this->pdo->lastInsertId();
53
	}
54
55
	public function addIndex($table, array $fields) {
56
		//Sort the fields so that the index is never created twice (col1, col2) then (col2, col1)
57
		sort($fields);
58
		$fields = array_map('strtolower', $fields);
59
		$fields = array_map('trim', $fields);
60
		$keyName = $this->quote(implode('_', $fields));
61
62
		$results = $this->pdo->query('SHOW INDEX FROM ' . $this->quote($table) . ' WHERE Key_Name = "' . $keyName . '"');
63
		if ($results && count($results->fetchAll()) == 0)  $this->pdo->query('CREATE INDEX ' . $keyName . ' ON ' . $this->quote($table) . ' (' . implode(', ', $fields) . ')');
64
	}
65
66
	public function optimiseColumns($table) {
67
		//TODO
68
		return;
69
	}
70
}
71