Completed
Pull Request — master (#49)
by Thomas
44:38 queued 08:11
created

Pgsql::bulkInsert()   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 28

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
dl 0
loc 28
ccs 0
cts 0
cp 0
rs 8.8497
c 0
b 0
f 0
cc 6
nc 4
nop 3
crap 42
1
<?php
2
3
namespace ORM\Dbal;
4
5
use ORM\Entity;
6
use ORM\Exception;
7
use ORM\QueryBuilder\QueryBuilder;
8
use PDO;
9
10
/**
11
 * Database abstraction for PostgreSQL databases
12
 *
13
 * @package ORM\Dbal
14
 * @author  Thomas Flori <[email protected]>
15
 */
16
class Pgsql extends Dbal
17
{
18
    protected static $typeMapping = [
19
        'integer'          => Type\Number::class,
20
        'smallint'         => Type\Number::class,
21
        'bigint'           => Type\Number::class,
22
        'numeric'          => Type\Number::class,
23
        'real'             => Type\Number::class,
24
        'double precision' => Type\Number::class,
25
        'money'            => Type\Number::class,
26
27
        'character varying' => Type\VarChar::class,
28
        'character'         => Type\VarChar::class,
29
30
        'text' => Type\Text::class,
31
32
        'date'                        => Type\DateTime::class,
33
        'timestamp without time zone' => Type\DateTime::class,
34
        'timestamp with time zone'    => Type\DateTime::class,
35
        'time without time zone'      => Type\Time::class,
36
        'time with time zone'         => Type\Time::class,
37
38
        'json'    => Type\Json::class,
39
        'boolean' => Type\Boolean::class,
40
    ];
41
42
    protected $booleanTrue  = 'true';
43
    protected $booleanFalse = 'false';
44
45 2
    public function insert(Entity $entity, $useAutoIncrement = true)
46
    {
47 2
        $statement = $this->buildInsertStatement($entity);
48 2
        $pdo       = $this->entityManager->getConnection();
49
50 2
        if ($useAutoIncrement && $entity::isAutoIncremented()) {
51 1
            $statement .= ' RETURNING ' . $entity::getColumnName($entity::getPrimaryKeyVars()[0]);
52 1
            $result    = $pdo->query($statement);
53 1
            $this->updateAutoincrement($entity, $result->fetchColumn());
54
        } else {
55 1
            $pdo->query($statement);
56
        }
57
58 2
        return $this->entityManager->sync($entity, true);
59
    }
60
61
    public function bulkInsert(array $entities, $update = true, $useAutoIncrement = true)
62
    {
63
        if (count($entities) === 0) {
64
            throw new InvalidArgument('$entities should not be empty');
65
        }
66
        $statement = $this->buildInsertStatement(...$entities);
67
        $pdo       = $this->entityManager->getConnection();
68
        $entity    = reset($entities);
69
70
        if ($update) {
71
            if ($useAutoIncrement && $entity::isAutoIncremented()) {
72
                $statement .= ' RETURNING ' . $entity::getColumnName($entity::getPrimaryKeyVars()[0]);
73
                $result = $pdo->query($statement);
74
                while ($id = $result->fetchColumn()) {
75
                    $this->updateAutoincrement($entity, $id);
76
                    $entity = next($entities);
77
                }
78
            } else {
79
                $pdo->query($statement);
80
            }
81
82
            $this->syncInserted(...$entities);
83
            return true;
84
        }
85
86
        $pdo->query($statement);
87
        return true;
88
    }
89
90 26
    public function describe($schemaTable)
91
    {
92 26
        $table = explode($this->identifierDivider, $schemaTable);
93 26
        list($schema, $table) = count($table) === 2 ? $table : [ 'public', $table[0] ];
94
95 26
        $query = new QueryBuilder('INFORMATION_SCHEMA.COLUMNS', '', $this->entityManager);
96 26
        $query->where('table_name', $table)->andWhere('table_schema', $schema);
97 26
        $query->columns([
98 26
            'column_name', 'column_default', 'data_type', 'is_nullable', 'character_maximum_length',
99
            'datetime_precision'
100
        ]);
101
102 26
        $result     = $this->entityManager->getConnection()->query($query->getQuery());
103 26
        $rawColumns = $result->fetchAll(PDO::FETCH_ASSOC);
104 26
        if (count($rawColumns) === 0) {
105 2
            throw new Exception('Unknown table ' . $schemaTable);
106
        }
107
108 24
        $cols = array_map(
109 24
            function ($columnDefinition) {
110 24
                if (isset(static::$typeMapping[$columnDefinition['data_type']])) {
111 17
                    $columnDefinition['type'] = static::$typeMapping[$columnDefinition['data_type']];
112
                }
113 24
                return new Column($this, $columnDefinition);
114 24
            },
115
            $rawColumns
116
        );
117
118
        return new Table($cols);
119
    }
120
}
121