depage-xmldb v2.3.1
XML documents in a relational database
Loading...
Searching...
No Matches
CaseUpdate.php
Go to the documentation of this file.
1<?php
2
12
13namespace Depage\XmlDb\Helpers;
14
27{
28 use IdentifierChecker;
29
33 public const DEFAULT_SIZE = 200;
34
35 protected $pdo;
36
40 protected $values = [];
41
49 public function __construct($pdo, protected string $table, protected int $size = self::DEFAULT_SIZE)
50 {
51 $this->pdo = $pdo;
52
53 $this->checkIdentifier($table, 'table');
54 }
55
56 public function isEmpty(): bool
57 {
58 return count($this->values) == 0;
59 }
60
63 public function isFull(): bool
64 {
65 return count($this->values) >= $this->size;
66 }
67
75 public function add($id, $value): void
76 {
77 $this->values[(int) $id] = $value;
78 }
79
88 public function write(string $column, array $conditions = []): void
89 {
90 if ($this->isEmpty()) {
91 return;
92 }
93
94 $column = $this->checkIdentifier($column);
95
96 $where = '';
97 $whereParams = [];
98 foreach ($conditions as $name => $value) {
99 $where .= ' AND ' . $this->checkIdentifier((string) $name) . ' = ?';
100 $whereParams[] = $value;
101 }
102
103 $chunks = array_chunk($this->values, $this->size, true);
104 $this->values = [];
105
106 foreach ($chunks as $chunk) {
107 $this->update($column, $where, $chunk, $whereParams);
108 }
109 }
110
114 protected function update(string $column, string $where, array $chunk, array $whereParams): void
115 {
116 $case = '';
117 $ids = [];
118 $params = [];
119
120 foreach ($chunk as $id => $value) {
121 $case .= ' WHEN ? THEN ?';
122 $params[] = $id;
123 $params[] = $value;
124 $ids[] = $id;
125 }
126
127 $query = $this->pdo->prepare(
128 "UPDATE {$this->table}
129 SET {$column} = CASE id{$case} END
130 WHERE id IN (" . implode(", ", array_fill(0, count($ids), '?')) . ")" . $where
131 );
132 $query->execute(array_merge(
133 $params,
134 $ids,
135 $whereParams
136 ));
137 }
138}
139
140/* vim:set ft=php sw=4 sts=4 fdm=marker et : */
isFull()
whether the buffer holds as many rows as a single statement writes
__construct($pdo, protected string $table, protected int $size=self::DEFAULT_SIZE)
write(string $column, array $conditions=[])
writes the collected values into $column and empties the buffer
add($id, $value)
collects the value one row should get; adding the same row again overwrites the value collected befor...
update(string $column, string $where, array $chunk, array $whereParams)
writes one chunk of rows with a single statement
const DEFAULT_SIZE
number of rows written with a single statement
$values
values to write, keyed by the id of the row