adapter.php 2.09 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
	 * @param array $input key->value pair, key has to be sanitized properly
46
	 * @throws \OC\HintException
47
	 * @return int count of inserted rows
48
	 */
49
50
51
52
53
54
	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
55
		$inserts = array_values($input);
56
		foreach($input as $key => $value) {
Jonny007-MKD's avatar
Jonny007-MKD committed
57
58
59
60
61
62
63
			$query .= '`' . $key . '`';
			if (is_null($value)) {
				$query .= ' IS NULL AND ';
			} else {
				$inserts[] = $value;
				$query .= ' = ? AND ';
			}
64
65
66
67
68
		}
		$query = substr($query, 0, strlen($query) - 5);
		$query .= ' HAVING COUNT(*) = 0';

		try {
69
			return $this->conn->executeUpdate($query, $inserts);
70
71
72
		} catch(\Doctrine\DBAL\DBALException $e) {
			$entry = 'DB Error: "'.$e->getMessage() . '"<br />';
			$entry .= 'Offending command was: ' . $query.'<br />';
73
			\OC_Log::write('core', $entry, \OC_Log::FATAL);
74
75
76
77
78
79
80
			$l = \OC::$server->getL10N('lib');
			throw new \OC\HintException(
				$l->t('Database Error'),
				$l->t('Please contact your system administrator.'),
				0,
				$e
			);
81
82
		}
	}
83
}