Passed
Push — master ( 2ac01c...f7152c )
by Roeland
13:31 queued 10s
created

AdapterPgSql::lastInsertId()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 2
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * @copyright Copyright (c) 2016, ownCloud, Inc.
4
 *
5
 * @author Bart Visscher <[email protected]>
6
 * @author Morris Jobke <[email protected]>
7
 *
8
 * @license AGPL-3.0
9
 *
10
 * This code is free software: you can redistribute it and/or modify
11
 * it under the terms of the GNU Affero General Public License, version 3,
12
 * as published by the Free Software Foundation.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17
 * GNU Affero General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU Affero General Public License, version 3,
20
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
21
 *
22
 */
23
24
25
namespace OC\DB;
26
27
use Doctrine\DBAL\DBALException;
28
29
class AdapterPgSql extends Adapter {
30
	protected $compatModePre9_5 = null;
31
32
	public function lastInsertId($table) {
33
		return $this->conn->fetchColumn('SELECT lastval()');
34
	}
35
36
	const UNIX_TIMESTAMP_REPLACEMENT = 'cast(extract(epoch from current_timestamp) as integer)';
37
	public function fixupStatement($statement) {
38
		$statement = str_replace( '`', '"', $statement );
39
		$statement = str_ireplace( 'UNIX_TIMESTAMP()', self::UNIX_TIMESTAMP_REPLACEMENT, $statement );
40
		return $statement;
41
	}
42
43
	/**
44
	 * @suppress SqlInjectionChecker
45
	 */
46
	public function insertIgnoreConflict(string $table,array $values) : int {
47
		if($this->isPre9_5CompatMode() === true) {
48
			return parent::insertIgnoreConflict($table, $values);
49
		}
50
51
		// "upsert" is only available since PgSQL 9.5, but the generic way
52
		// would leave error logs in the DB.
53
		$builder = $this->conn->getQueryBuilder();
54
		$builder->insert($table);
55
		foreach ($values as $key => $value) {
56
			$builder->setValue($key, $builder->createNamedParameter($value));
57
		}
58
		$queryString = $builder->getSQL() . ' ON CONFLICT DO NOTHING';
59
		return $this->conn->executeUpdate($queryString, $builder->getParameters(), $builder->getParameterTypes());
60
	}
61
62
	protected function isPre9_5CompatMode(): bool {
63
		if($this->compatModePre9_5 !== null) {
64
			return $this->compatModePre9_5;
65
		}
66
67
		$version = $this->conn->fetchColumn('SHOW SERVER_VERSION');
68
		$this->compatModePre9_5 = version_compare($version, '9.5', '<');
69
70
		return $this->compatModePre9_5;
71
	}
72
}
73