Debian Codegraph @

includes/libs/rdbms/querybuilder/InsertQueryBuilder.php

raw symbols SCIP
1 <?php
2
3 namespace Wikimedia\Rdbms;
4
5 use InvalidArgumentException;
6 use UnexpectedValueException;
7
8 /**
9 * Build INSERT queries with a fluent interface.
10 *
11 * Each query builder object must be used for a single database query only,
12 * and not be reused afterwards. To run multiple similar queries, you can
13 * create a query builder to set up most of your query, which you can use
14 * as a "template" to clone. You can then modify the cloned object for
15 * each individual query.
16 *
17 * @since 1.41
18 * @stable to extend
19 * @ingroup Database
20 */
21 class InsertQueryBuilder {
22 /**
23 * @var string The table name to be passed to IDatabase::insert()
24 */
25 private $table = '';
26
27 /**
28 * @var list<array> The rows to be passed to IDatabase::insert()
29 */
30 private $rows = [];
31
32 /**
33 * @var string The caller (function name) to be passed to IDatabase::insert()
34 */
35 private $caller = __CLASS__;
36
37 /**
38 * @var bool whether this is an upsert or not
39 */
40 private $upsert = false;
41
42 /**
43 * @var array The set values to be passed to IDatabase::upsert()
44 */
45 private $set = [];
46
47 /**
48 * @var string[] The unique keys to be passed to IDatabase::upsert()
49 */
50 private $uniqueIndexFields = [];
51
52 /**
53 * @var array The options to be passed to IDatabase::insert()
54 */
55 protected $options = [];
56
57 /** @var IDatabase */
58 protected $db;
59
60 /**
61 * Only for use in subclasses. To create a InsertQueryBuilder instance,
62 * use `$db->newInsertQueryBuilder()` instead.
63 *
64 * @param IDatabase $db
65 */
66 public function __construct( IDatabase $db ) {
67 $this->db = $db;
68 }
69
70 /**
71 * Change the IDatabase object the query builder is bound to. The specified
72 * IDatabase will subsequently be used to execute the query.
73 *
74 * @param IDatabase $db
75 * @return $this
76 */
77 public function connection( IDatabase $db ) {
78 if ( $this->db->getType() !== $db->getType() ) {
79 throw new InvalidArgumentException(
80 __METHOD__ . ' cannot switch to a database of a different type.'
81 );
82 }
83 $this->db = $db;
84 return $this;
85 }
86
87 /**
88 * Set the query parameters to the given values, appending to the values
89 * which were already set. This can be used to interface with legacy code.
90 * If a key is omitted, the previous value will be retained.
91 *
92 * The parameters must be formatted as required by Database::insert.
93 *
94 * @param array $info Associative array of query info, with keys:
95 * - table: The table name to be passed to Database::insert()
96 * - rows: The rows to be inserted
97 * - options: The query options
98 * - upsert: Whether it's insert or upsert
99 * - uniqueIndexFields: Fields of the unique index
100 * - set: The set array
101 * - caller: The caller signature
102 *
103 * @return $this
104 */
105 public function queryInfo( $info ) {
106 if ( isset( $info['table'] ) ) {
107 $this->table( $info['table'] );
108 }
109 if ( isset( $info['rows'] ) ) {
110 $this->rows( $info['rows'] );
111 }
112 if ( isset( $info['options'] ) ) {
113 $this->options( (array)$info['options'] );
114 }
115 if ( isset( $info['upsert'] ) ) {
116 $this->onDuplicateKeyUpdate();
117 }
118 if ( isset( $info['uniqueIndexFields'] ) ) {
119 $this->uniqueIndexFields( (array)$info['uniqueIndexFields'] );
120 }
121 if ( isset( $info['set'] ) ) {
122 $this->set( (array)$info['set'] );
123 }
124 if ( isset( $info['caller'] ) ) {
125 $this->caller( $info['caller'] );
126 }
127 return $this;
128 }
129
130 /**
131 * Manually set the table name to be passed to IDatabase::insert()
132 *
133 * @param string $table The unqualified name of a table
134 * @param-taint $table exec_sql
135 * @return $this
136 */
137 public function table( $table ) {
138 $this->table = $table;
139 return $this;
140 }
141
142 /**
143 * Set table for the query. Alias for table().
144 *
145 * @param string $table The unqualified name of a table
146 * @param-taint $table exec_sql
147 * @return $this
148 */
149 public function insertInto( string $table ) {
150 return $this->table( $table );
151 }
152
153 /**
154 * Set table for the query. Alias for table().
155 *
156 * @param string $table The unqualified name of a table
157 * @param-taint $table exec_sql
158 * @return $this
159 */
160 public function insert( string $table ) {
161 return $this->table( $table );
162 }
163
164 /**
165 * Manually set an option in the $options array to be passed to
166 * IDatabase::insert()
167 *
168 * @param string $name The option name
169 * @param mixed $value The option value, or null for a boolean option
170 * @return $this
171 */
172 public function option( $name, $value = null ) {
173 if ( $value === null ) {
174 $this->options[] = $name;
175 } else {
176 $this->options[$name] = $value;
177 }
178 return $this;
179 }
180
181 /**
182 * Manually set multiple options in the $options array to be passed to
183 * IDatabase::insert().
184 *
185 * @param array $options
186 * @return $this
187 */
188 public function options( array $options ) {
189 $this->options = array_merge( $this->options, $options );
190 return $this;
191 }
192
193 /**
194 * Add rows to be inserted.
195 *
196 * @param list<array> $rows
197 * $rows should be an integer-keyed list of such string-keyed maps, defining a list of new rows.
198 * The keys in each map must be identical to each other and in the same order.
199 * The rows must not collide with each other.
200 *
201 * @return $this
202 */
203 public function rows( array $rows ) {
204 $this->rows = array_merge( $this->rows, $rows );
205 return $this;
206 }
207
208 /**
209 * Add one row to be inserted.
210 *
211 * @param array $row
212 * $row must be a string-keyed map of (column name => value) defining a new row. Values are
213 * treated as literals and quoted appropriately; null is interpreted as NULL.
214 *
215 * @return $this
216 */
217 public function row( array $row ) {
218 $this->rows[] = $row;
219 return $this;
220 }
221
222 /**
223 * Enable the IGNORE option.
224 *
225 * Skip insertion of rows that would cause unique key conflicts.
226 * IDatabase::affectedRows() can be used to determine how many rows were inserted.
227 *
228 * @return $this
229 */
230 public function ignore() {
231 $this->options[] = 'IGNORE';
232 return $this;
233 }
234
235 /**
236 * Do an update instead of insert
237 *
238 * @return $this
239 */
240 public function onDuplicateKeyUpdate() {
241 $this->upsert = true;
242 return $this;
243 }
244
245 /**
246 * Set the unique index fields
247 *
248 * @param string|string[] $uniqueIndexFields
249 * @return $this
250 */
251 public function uniqueIndexFields( $uniqueIndexFields ) {
252 if ( is_string( $uniqueIndexFields ) ) {
253 $uniqueIndexFields = [ $uniqueIndexFields ];
254 }
255 $this->uniqueIndexFields = $uniqueIndexFields;
256 return $this;
257 }
258
259 /**
260 * Add SET part to the query. It takes an array containing arrays of column names map to
261 * the set values.
262 *
263 * @param string|array<string,?scalar|RawSQLValue>|array<int,string> $set
264 * @param-taint $set exec_sql_numkey
265 *
266 * Combination map/list where each string-keyed entry maps a column
267 * to a literal assigned value and each integer-keyed value is a SQL expression in the
268 * format of a column assignment within UPDATE...SET. The (column => value) entries are
269 * convenient due to automatic value quoting and conversion of null to NULL. The SQL
270 * assignment format is useful for updates like "column = column + X". All assignments
271 * have no defined execution order, so they should not depend on each other. Do not
272 * modify AUTOINCREMENT or UUID columns in assignments.
273 *
274 * Untrusted user input is safe in the values of string keys, however untrusted
275 * input must not be used in the array key names or in the values of numeric keys.
276 * Escaping of untrusted input used in values of numeric keys should be done via
277 * IDatabase::addQuotes()
278 *
279 * @return $this
280 */
281 public function set( $set ) {
282 if ( is_array( $set ) ) {
283 foreach ( $set as $key => $value ) {
284 if ( is_int( $key ) ) {
285 $this->set[] = $value;
286 } else {
287 $this->set[$key] = $value;
288 }
289 }
290 } else {
291 $this->set[] = $set;
292 }
293 return $this;
294 }
295
296 /**
297 * Add set values to the query. Alias for set().
298 *
299 * @param string|array<string,?scalar|RawSQLValue>|array<int,string> $set
300 * @param-taint $set exec_sql_numkey
301 * @return $this
302 */
303 public function andSet( $set ) {
304 return $this->set( $set );
305 }
306
307 /**
308 * Set the method name to be included in an SQL comment.
309 *
310 * @param string $fname
311 * @param-taint $fname exec_sql
312 * @return $this
313 */
314 public function caller( $fname ) {
315 $this->caller = $fname;
316 return $this;
317 }
318
319 /**
320 * Run the constructed INSERT query.
321 */
322 public function execute(): void {
323 if ( !$this->rows ) {
324 throw new UnexpectedValueException(
325 __METHOD__ . ' can\'t have empty $rows value' );
326 }
327 if ( $this->table === '' ) {
328 throw new UnexpectedValueException(
329 __METHOD__ . ' expects table not to be empty' );
330 }
331 if ( $this->upsert && ( !$this->set || !$this->uniqueIndexFields ) ) {
332 throw new UnexpectedValueException(
333 __METHOD__ . ' called with upsert but no set value or unique key has been provided' );
334 }
335 if ( !$this->upsert && ( $this->set || $this->uniqueIndexFields ) ) {
336 throw new UnexpectedValueException(
337 __METHOD__ . ' is not called with upsert but set value or unique key has been provided' );
338 }
339 if ( $this->upsert ) {
340 $this->db->upsert( $this->table, $this->rows, [ $this->uniqueIndexFields ], $this->set, $this->caller );
341 return;
342 }
343 $this->db->insert( $this->table, $this->rows, $this->caller, $this->options );
344 }
345
346 /**
347 * Get an associative array describing the query in terms of its raw parameters to
348 * Database::insert(). This can be used to interface with legacy code.
349 *
350 * @return array The query info array, with keys:
351 * - table: The table name
352 * - rows: The rows array
353 * - options: The query options
354 * - upsert: Whether it's insert or upsert
355 * - uniqueIndexFields: Fields of the unique index
356 * - set: The set array
357 * - caller: The caller signature
358 */
359 public function getQueryInfo() {
360 $info = [
361 'table' => $this->table,
362 'rows' => $this->rows,
363 'upsert' => $this->upsert,
364 'set' => $this->set,
365 'uniqueIndexFields' => $this->uniqueIndexFields,
366 'options' => $this->options,
367 ];
368 if ( $this->caller !== __CLASS__ ) {
369 $info['caller'] = $this->caller;
370 }
371 return $info;
372 }
373 }