|
12 | 12 |
|
13 | 13 | namespace chillerlan\Database\Dialects; |
14 | 14 |
|
| 15 | +use chillerlan\Database\Query\QueryException; |
| 16 | + |
15 | 17 | class Postgres extends DialectAbstract{ |
16 | 18 |
|
17 | 19 | protected $quotes = ['"', '"']; |
@@ -53,6 +55,51 @@ public function select(array $cols, array $from, string $where = null, $limit = |
53 | 55 | return $sql; |
54 | 56 | } |
55 | 57 |
|
| 58 | + /** |
| 59 | + * @link https://www.postgresql.org/docs/9.5/static/sql-insert.html#SQL-ON-CONFLICT |
| 60 | + * |
| 61 | + * @inheritdoc |
| 62 | + */ |
| 63 | + public function insert(string $table, array $fields, string $onConflict = null, string $conflictTarget = null):array{ |
| 64 | + $sql = parent::insert($table, $fields); |
| 65 | + |
| 66 | + if(in_array($onConflict, ['IGNORE', 'REPLACE'], true)){ |
| 67 | + |
| 68 | + if(empty($conflictTarget)){ |
| 69 | + throw new QueryException('postgres insert on conflict: no conflict target given'); |
| 70 | + } |
| 71 | + |
| 72 | + $sql[] = 'ON CONFLICT ('.$this->quote($conflictTarget).') DO'; |
| 73 | + |
| 74 | + switch($onConflict){ |
| 75 | + case 'IGNORE': |
| 76 | + $sql[] = 'NOTHING'; |
| 77 | + break; |
| 78 | + case 'REPLACE': |
| 79 | + $sql[] = $this->onConflictUpdate($fields); |
| 80 | + break; |
| 81 | + } |
| 82 | + |
| 83 | + } |
| 84 | + |
| 85 | + return $sql; |
| 86 | + } |
| 87 | + |
| 88 | + /** |
| 89 | + * @param array $fields |
| 90 | + * |
| 91 | + * @return string |
| 92 | + */ |
| 93 | + protected function onConflictUpdate(array $fields):string { |
| 94 | + $onConflictUpdate = []; |
| 95 | + |
| 96 | + foreach($fields as $f){ |
| 97 | + $onConflictUpdate[] = $this->quote($f).' = EXCLUDED.'.$this->quote($f); |
| 98 | + } |
| 99 | + |
| 100 | + return 'UPDATE SET '.implode(', ', $onConflictUpdate); |
| 101 | + } |
| 102 | + |
56 | 103 | /** @inheritdoc */ |
57 | 104 | public function createDatabase(string $dbname, bool $ifNotExists = null, string $collate = null):array{ |
58 | 105 | $sql = ['CREATE DATABASE']; |
@@ -295,20 +342,3 @@ public function showCreateTable(string $table):array{ |
295 | 342 | } |
296 | 343 |
|
297 | 344 | } |
298 | | - |
299 | | - |
300 | | -/* |
301 | | -create table querytest |
302 | | -( |
303 | | - id INTEGER |
304 | | - primary key, |
305 | | - hash VARCHAR(32), |
306 | | - data TEXT, |
307 | | - value DECIMAL(9,6), |
308 | | - active BOOLEAN, |
309 | | - created TIMESTAMP default 'CURRENT_TIMESTAMP' |
310 | | -) |
311 | | -; |
312 | | -
|
313 | | -
|
314 | | -*/ |
|
0 commit comments