Completed
Branch feature/pre-split (42159e)
by Anton
05:36
created

PostgresInsertQuery::run()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 0
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * Spiral Framework.
4
 *
5
 * @license   MIT
6
 * @author    Anton Titov (Wolfy-J)
7
 */
8
9
namespace Spiral\Database\Drivers\Postgres;
10
11
use Spiral\Database\Builders\InsertQuery;
12
use Spiral\Database\Entities\QueryCompiler as AbstractCompiler;
13
use Spiral\Database\Exceptions\BuilderException;
14
15
/**
16
 * Postgres driver requires little bit different way to handle last insert id.
17
 */
18
class PostgresInsertQuery extends InsertQuery
19
{
20
    /**
21
     * {@inheritdoc}
22
     */
23
    public function sqlStatement(AbstractCompiler $compiler = null): string
24
    {
25
        if (
26
            !$this->driver instanceof PostgresDriver
27
            || (!empty($compiler) && !$compiler instanceof PostgresCompiler)
28
        ) {
29
            throw new BuilderException(
30
                'Postgres InsertQuery can be used only with Postgres driver and compiler'
31
            );
32
        }
33
34
        if (empty($compiler)) {
35
            $compiler = $this->compiler->resetQuoter();
36
        }
37
38
        /**
39
         * @var PostgresDriver   $driver
40
         * @var PostgresCompiler $compiler
41
         */
42
        return $compiler->compileInsert(
43
            $this->table,
44
            $this->columns,
45
            $this->rowsets,
46
            $this->driver->getPrimary($this->compiler->getPrefix(), $this->table)
47
        );
48
    }
49
50
    /**
51
     * {@inheritdoc}
52
     */
53
    public function run(): int
54
    {
55
        return (int)$this->driver->statement(
56
            $this->sqlStatement(),
57
            $this->getParameters()
58
        )->fetchColumn();
59
    }
60
}
61