Passed
Push — master ( 380864...509b8c )
by Richard
01:39
created

MysqlAdapter::isNotSavableType()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 2
nc 4
nop 3
dl 0
loc 3
rs 9.2
c 0
b 0
f 0
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
34
			try {
35
				if (!$this->pdo->query('ALTER TABLE ' . $table . ' ADD ' . $this->quote($key) . ' ' . $type)) throw new \Exception('Could not alter table');
36
			}
37
			catch (\Exception $e) {
38
				$this->pdo->query('ALTER TABLE ' . $table . ' MODIFY ' . $this->quote($key) . ' ' . $type);
39
			}
40
		}
41
    }
42
43
	public function alterDatabase($table, array $primaryKey, $data) {
44
		$this->generalEditor->createTable($table, $primaryKey, $data);
45
        $this->alterColumns($table, $primaryKey, $data);
46
	}
47
48
	public function lastInsertId() {
49
		return $this->pdo->lastInsertId();
50
	}
51
52
	public function addIndex($table, array $fields) {
53
		//Sort the fields so that the index is never created twice (col1, col2) then (col2, col1)
54
		sort($fields);
55
		$fields = array_map('strtolower', $fields);
56
		$fields = array_map('trim', $fields);
57
		$keyName = $this->quote(implode('_', $fields));
58
59
		$results = $this->pdo->query('SHOW INDEX FROM ' . $this->quote($table) . ' WHERE Key_Name = "' . $keyName . '"');
60
		if ($results && count($results->fetchAll()) == 0)  $this->pdo->query('CREATE INDEX ' . $keyName . ' ON ' . $this->quote($table) . ' (' . implode(', ', $fields) . ')');
61
	}
62
63
	public function optimiseColumns($table) {
64
		//TODO
65
		return;
66
	}
67
}
68