adapter.php 1.94 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
<?php
/**
 * Copyright (c) 2013 Bart Visscher <bartv@thisnet.nl>
 * This file is licensed under the Affero General Public License version 3 or
 * later.
 * See the COPYING-README file.
 */

namespace OC\DB;

11
12
13
14
/**
 * This handles the way we use to write queries, into something that can be
 * handled by the database abstraction layer.
 */
15
class Adapter {
16
17
18
19

	/**
	 * @var \OC\DB\Connection $conn
	 */
20
21
22
23
24
	protected $conn;

	public function __construct($conn) {
		$this->conn = $conn;
	}
25

26
27
28
29
	/**
	 * @param string $table name
	 * @return int id of last insert statement
	 */
30
31
32
	public function lastInsertId($table) {
		return $this->conn->realLastInsertId($table);
	}
33

34
	/**
35
	 * @param string $statement that needs to be changed so the db can handle it
36
37
	 * @return string changed statement
	 */
38
39
40
	public function fixupStatement($statement) {
		return $statement;
	}
41

42
	/**
43
	 * insert the @input values when they do not exist yet
44
	 * @param string $table name
45
46
	 * @param array $input key->value pairs
	 * @return int count of inserted rows
47
	 */
48
49
50
51
52
53
	public function insertIfNotExist($table, $input) {
		$query = 'INSERT INTO `' .$table . '` (`'
			. implode('`,`', array_keys($input)) . '`) SELECT '
			. str_repeat('?,', count($input)-1).'? ' // Is there a prettier alternative?
			. 'FROM `' . $table . '` WHERE ';

Jonny007-MKD's avatar
Jonny007-MKD committed
54
		$inserts = array_values($input);
55
		foreach($input as $key => $value) {
Jonny007-MKD's avatar
Jonny007-MKD committed
56
57
58
59
60
61
62
			$query .= '`' . $key . '`';
			if (is_null($value)) {
				$query .= ' IS NULL AND ';
			} else {
				$inserts[] = $value;
				$query .= ' = ? AND ';
			}
63
64
65
66
67
		}
		$query = substr($query, 0, strlen($query) - 5);
		$query .= ' HAVING COUNT(*) = 0';

		try {
68
			return $this->conn->executeUpdate($query, $inserts);
69
70
71
		} catch(\Doctrine\DBAL\DBALException $e) {
			$entry = 'DB Error: "'.$e->getMessage() . '"<br />';
			$entry .= 'Offending command was: ' . $query.'<br />';
72
			\OC_Log::write('core', $entry, \OC_Log::FATAL);
73
			error_log('DB error: ' . $entry);
74
			\OC_Template::printErrorPage( $entry );
75
76
		}
	}
77
}