MediaWiki  master
DatabaseSQLTest.php
Go to the documentation of this file.
1 <?php
2 
10 
16 
19 
21  private $database;
22 
23  protected function setUp() {
24  parent::setUp();
25  $this->database = new DatabaseTestHelper( __CLASS__, [ 'cliMode' => true ] );
26  }
27 
28  protected function assertLastSql( $sqlText ) {
29  $this->assertEquals(
30  $sqlText,
31  $this->database->getLastSqls()
32  );
33  }
34 
35  protected function assertLastSqlDb( $sqlText, DatabaseTestHelper $db ) {
36  $this->assertEquals( $sqlText, $db->getLastSqls() );
37  }
38 
52  public function testSelect( $sql, $sqlText ) {
53  $this->database->select(
54  $sql['tables'],
55  $sql['fields'],
56  $sql['conds'] ?? [],
57  __METHOD__,
58  $sql['options'] ?? [],
59  $sql['join_conds'] ?? []
60  );
61  $this->assertLastSql( $sqlText );
62  }
63 
64  public static function provideSelect() {
65  return [
66  [
67  [
68  'tables' => 'table',
69  'fields' => [ 'field', 'alias' => 'field2' ],
70  'conds' => [ 'alias' => 'text' ],
71  ],
72  "SELECT field,field2 AS alias " .
73  "FROM table " .
74  "WHERE alias = 'text'"
75  ],
76  [
77  [
78  'tables' => 'table',
79  'fields' => [ 'field', 'alias' => 'field2' ],
80  'conds' => 'alias = \'text\'',
81  ],
82  "SELECT field,field2 AS alias " .
83  "FROM table " .
84  "WHERE alias = 'text'"
85  ],
86  [
87  [
88  'tables' => 'table',
89  'fields' => [ 'field', 'alias' => 'field2' ],
90  'conds' => [],
91  ],
92  "SELECT field,field2 AS alias " .
93  "FROM table"
94  ],
95  [
96  [
97  'tables' => 'table',
98  'fields' => [ 'field', 'alias' => 'field2' ],
99  'conds' => '',
100  ],
101  "SELECT field,field2 AS alias " .
102  "FROM table"
103  ],
104  [
105  [
106  'tables' => 'table',
107  'fields' => [ 'field', 'alias' => 'field2' ],
108  'conds' => '0', // T188314
109  ],
110  "SELECT field,field2 AS alias " .
111  "FROM table " .
112  "WHERE 0"
113  ],
114  [
115  [
116  // 'tables' with space prepended indicates pre-escaped table name
117  'tables' => ' table LEFT JOIN table2',
118  'fields' => [ 'field' ],
119  'conds' => [ 'field' => 'text' ],
120  ],
121  "SELECT field FROM table LEFT JOIN table2 WHERE field = 'text'"
122  ],
123  [
124  [
125  // Empty 'tables' is allowed
126  'tables' => '',
127  'fields' => [ 'SPECIAL_QUERY()' ],
128  ],
129  "SELECT SPECIAL_QUERY()"
130  ],
131  [
132  [
133  'tables' => 'table',
134  'fields' => [ 'field', 'alias' => 'field2' ],
135  'conds' => [ 'alias' => 'text' ],
136  'options' => [ 'LIMIT' => 1, 'ORDER BY' => 'field' ],
137  ],
138  "SELECT field,field2 AS alias " .
139  "FROM table " .
140  "WHERE alias = 'text' " .
141  "ORDER BY field " .
142  "LIMIT 1"
143  ],
144  [
145  [
146  'tables' => [ 'table', 't2' => 'table2' ],
147  'fields' => [ 'tid', 'field', 'alias' => 'field2', 't2.id' ],
148  'conds' => [ 'alias' => 'text' ],
149  'options' => [ 'LIMIT' => 1, 'ORDER BY' => 'field' ],
150  'join_conds' => [ 't2' => [
151  'LEFT JOIN', 'tid = t2.id'
152  ] ],
153  ],
154  "SELECT tid,field,field2 AS alias,t2.id " .
155  "FROM table LEFT JOIN table2 t2 ON ((tid = t2.id)) " .
156  "WHERE alias = 'text' " .
157  "ORDER BY field " .
158  "LIMIT 1"
159  ],
160  [
161  [
162  'tables' => [ 'table', 't2' => 'table2' ],
163  'fields' => [ 'tid', 'field', 'alias' => 'field2', 't2.id' ],
164  'conds' => [ 'alias' => 'text' ],
165  'options' => [ 'LIMIT' => 1, 'GROUP BY' => 'field', 'HAVING' => 'COUNT(*) > 1' ],
166  'join_conds' => [ 't2' => [
167  'LEFT JOIN', 'tid = t2.id'
168  ] ],
169  ],
170  "SELECT tid,field,field2 AS alias,t2.id " .
171  "FROM table LEFT JOIN table2 t2 ON ((tid = t2.id)) " .
172  "WHERE alias = 'text' " .
173  "GROUP BY field HAVING COUNT(*) > 1 " .
174  "LIMIT 1"
175  ],
176  [
177  [
178  'tables' => [ 'table', 't2' => 'table2' ],
179  'fields' => [ 'tid', 'field', 'alias' => 'field2', 't2.id' ],
180  'conds' => [ 'alias' => 'text' ],
181  'options' => [
182  'LIMIT' => 1,
183  'GROUP BY' => [ 'field', 'field2' ],
184  'HAVING' => [ 'COUNT(*) > 1', 'field' => 1 ]
185  ],
186  'join_conds' => [ 't2' => [
187  'LEFT JOIN', 'tid = t2.id'
188  ] ],
189  ],
190  "SELECT tid,field,field2 AS alias,t2.id " .
191  "FROM table LEFT JOIN table2 t2 ON ((tid = t2.id)) " .
192  "WHERE alias = 'text' " .
193  "GROUP BY field,field2 HAVING (COUNT(*) > 1) AND field = '1' " .
194  "LIMIT 1"
195  ],
196  [
197  [
198  'tables' => [ 'table' ],
199  'fields' => [ 'alias' => 'field' ],
200  'conds' => [ 'alias' => [ 1, 2, 3, 4 ] ],
201  ],
202  "SELECT field AS alias " .
203  "FROM table " .
204  "WHERE alias IN ('1','2','3','4')"
205  ],
206  [
207  [
208  'tables' => 'table',
209  'fields' => [ 'field' ],
210  'options' => [ 'USE INDEX' => [ 'table' => 'X' ] ],
211  ],
212  // No-op by default
213  "SELECT field FROM table"
214  ],
215  [
216  [
217  'tables' => 'table',
218  'fields' => [ 'field' ],
219  'options' => [ 'IGNORE INDEX' => [ 'table' => 'X' ] ],
220  ],
221  // No-op by default
222  "SELECT field FROM table"
223  ],
224  [
225  [
226  'tables' => 'table',
227  'fields' => [ 'field' ],
228  'options' => [ 'DISTINCT' ],
229  ],
230  "SELECT DISTINCT field FROM table"
231  ],
232  [
233  [
234  'tables' => 'table',
235  'fields' => [ 'field' ],
236  'options' => [ 'LOCK IN SHARE MODE' ],
237  ],
238  "SELECT field FROM table LOCK IN SHARE MODE"
239  ],
240  [
241  [
242  'tables' => 'table',
243  'fields' => [ 'field' ],
244  'options' => [ 'EXPLAIN' => true ],
245  ],
246  'EXPLAIN SELECT field FROM table'
247  ],
248  [
249  [
250  'tables' => 'table',
251  'fields' => [ 'field' ],
252  'options' => [ 'FOR UPDATE' ],
253  ],
254  "SELECT field FROM table FOR UPDATE"
255  ],
256  ];
257  }
258 
263  public function testLockForUpdate( $sql, $sqlText ) {
264  $this->database->startAtomic( __METHOD__ );
265  $this->database->lockForUpdate(
266  $sql['tables'],
267  $sql['conds'] ?? [],
268  __METHOD__,
269  $sql['options'] ?? [],
270  $sql['join_conds'] ?? []
271  );
272  $this->database->endAtomic( __METHOD__ );
273 
274  $this->assertLastSql( "BEGIN; $sqlText; COMMIT" );
275  }
276 
277  public static function provideLockForUpdate() {
278  return [
279  [
280  [
281  'tables' => [ 'table' ],
282  'conds' => [ 'field' => [ 1, 2, 3, 4 ] ],
283  ],
284  "SELECT COUNT(*) AS rowcount FROM " .
285  "(SELECT 1 FROM table WHERE field IN ('1','2','3','4') " .
286  "FOR UPDATE) tmp_count"
287  ],
288  [
289  [
290  'tables' => [ 'table', 't2' => 'table2' ],
291  'conds' => [ 'field' => 'text' ],
292  'options' => [ 'LIMIT' => 1, 'ORDER BY' => 'field' ],
293  'join_conds' => [ 't2' => [
294  'LEFT JOIN', 'tid = t2.id'
295  ] ],
296  ],
297  "SELECT COUNT(*) AS rowcount FROM " .
298  "(SELECT 1 FROM table LEFT JOIN table2 t2 ON ((tid = t2.id)) " .
299  "WHERE field = 'text' ORDER BY field LIMIT 1 FOR UPDATE) tmp_count"
300  ],
301  [
302  [
303  'tables' => 'table',
304  ],
305  "SELECT COUNT(*) AS rowcount FROM " .
306  "(SELECT 1 FROM table FOR UPDATE) tmp_count"
307  ],
308  ];
309  }
310 
317  public function testSelectRowCount( $sql, $sqlText ) {
318  $this->database->selectRowCount(
319  $sql['tables'],
320  $sql['field'],
321  $sql['conds'] ?? [],
322  __METHOD__,
323  $sql['options'] ?? [],
324  $sql['join_conds'] ?? []
325  );
326  $this->assertLastSql( $sqlText );
327  }
328 
329  public static function provideSelectRowCount() {
330  return [
331  [
332  [
333  'tables' => 'table',
334  'field' => [ '*' ],
335  'conds' => [ 'field' => 'text' ],
336  ],
337  "SELECT COUNT(*) AS rowcount FROM " .
338  "(SELECT 1 FROM table WHERE field = 'text' ) tmp_count"
339  ],
340  [
341  [
342  'tables' => 'table',
343  'field' => [ 'column' ],
344  'conds' => [ 'field' => 'text' ],
345  ],
346  "SELECT COUNT(*) AS rowcount FROM " .
347  "(SELECT 1 FROM table WHERE field = 'text' AND (column IS NOT NULL) ) tmp_count"
348  ],
349  [
350  [
351  'tables' => 'table',
352  'field' => [ 'alias' => 'column' ],
353  'conds' => [ 'field' => 'text' ],
354  ],
355  "SELECT COUNT(*) AS rowcount FROM " .
356  "(SELECT 1 FROM table WHERE field = 'text' AND (column IS NOT NULL) ) tmp_count"
357  ],
358  [
359  [
360  'tables' => 'table',
361  'field' => [ 'alias' => 'column' ],
362  'conds' => '',
363  ],
364  "SELECT COUNT(*) AS rowcount FROM " .
365  "(SELECT 1 FROM table WHERE (column IS NOT NULL) ) tmp_count"
366  ],
367  [
368  [
369  'tables' => 'table',
370  'field' => [ 'alias' => 'column' ],
371  'conds' => false,
372  ],
373  "SELECT COUNT(*) AS rowcount FROM " .
374  "(SELECT 1 FROM table WHERE (column IS NOT NULL) ) tmp_count"
375  ],
376  [
377  [
378  'tables' => 'table',
379  'field' => [ 'alias' => 'column' ],
380  'conds' => null,
381  ],
382  "SELECT COUNT(*) AS rowcount FROM " .
383  "(SELECT 1 FROM table WHERE (column IS NOT NULL) ) tmp_count"
384  ],
385  [
386  [
387  'tables' => 'table',
388  'field' => [ 'alias' => 'column' ],
389  'conds' => '1',
390  ],
391  "SELECT COUNT(*) AS rowcount FROM " .
392  "(SELECT 1 FROM table WHERE (1) AND (column IS NOT NULL) ) tmp_count"
393  ],
394  [
395  [
396  'tables' => 'table',
397  'field' => [ 'alias' => 'column' ],
398  'conds' => '0',
399  ],
400  "SELECT COUNT(*) AS rowcount FROM " .
401  "(SELECT 1 FROM table WHERE (0) AND (column IS NOT NULL) ) tmp_count"
402  ],
403  ];
404  }
405 
412  public function testUpdate( $sql, $sqlText ) {
413  $this->database->update(
414  $sql['table'],
415  $sql['values'],
416  $sql['conds'],
417  __METHOD__,
418  $sql['options'] ?? []
419  );
420  $this->assertLastSql( $sqlText );
421  }
422 
423  public static function provideUpdate() {
424  return [
425  [
426  [
427  'table' => 'table',
428  'values' => [ 'field' => 'text', 'field2' => 'text2' ],
429  'conds' => [ 'alias' => 'text' ],
430  ],
431  "UPDATE table " .
432  "SET field = 'text'" .
433  ",field2 = 'text2' " .
434  "WHERE alias = 'text'"
435  ],
436  [
437  [
438  'table' => 'table',
439  'values' => [ 'field = other', 'field2' => 'text2' ],
440  'conds' => [ 'id' => '1' ],
441  ],
442  "UPDATE table " .
443  "SET field = other" .
444  ",field2 = 'text2' " .
445  "WHERE id = '1'"
446  ],
447  [
448  [
449  'table' => 'table',
450  'values' => [ 'field = other', 'field2' => 'text2' ],
451  'conds' => '*',
452  ],
453  "UPDATE table " .
454  "SET field = other" .
455  ",field2 = 'text2'"
456  ],
457  ];
458  }
459 
464  public function testDelete( $sql, $sqlText ) {
465  $this->database->delete(
466  $sql['table'],
467  $sql['conds'],
468  __METHOD__
469  );
470  $this->assertLastSql( $sqlText );
471  }
472 
473  public static function provideDelete() {
474  return [
475  [
476  [
477  'table' => 'table',
478  'conds' => [ 'alias' => 'text' ],
479  ],
480  "DELETE FROM table " .
481  "WHERE alias = 'text'"
482  ],
483  [
484  [
485  'table' => 'table',
486  'conds' => '*',
487  ],
488  "DELETE FROM table"
489  ],
490  ];
491  }
492 
497  public function testUpsert( $sql, $sqlText ) {
498  $this->database->upsert(
499  $sql['table'],
500  $sql['rows'],
501  $sql['uniqueIndexes'],
502  $sql['set'],
503  __METHOD__
504  );
505  $this->assertLastSql( $sqlText );
506  }
507 
508  public static function provideUpsert() {
509  return [
510  [
511  [
512  'table' => 'upsert_table',
513  'rows' => [ 'field' => 'text', 'field2' => 'text2' ],
514  'uniqueIndexes' => [ 'field' ],
515  'set' => [ 'field' => 'set' ],
516  ],
517  "BEGIN; " .
518  "UPDATE upsert_table " .
519  "SET field = 'set' " .
520  "WHERE ((field = 'text')); " .
521  "INSERT IGNORE INTO upsert_table " .
522  "(field,field2) " .
523  "VALUES ('text','text2'); " .
524  "COMMIT"
525  ],
526  ];
527  }
528 
533  public function testDeleteJoin( $sql, $sqlText ) {
534  $this->database->deleteJoin(
535  $sql['delTable'],
536  $sql['joinTable'],
537  $sql['delVar'],
538  $sql['joinVar'],
539  $sql['conds'],
540  __METHOD__
541  );
542  $this->assertLastSql( $sqlText );
543  }
544 
545  public static function provideDeleteJoin() {
546  return [
547  [
548  [
549  'delTable' => 'table',
550  'joinTable' => 'table_join',
551  'delVar' => 'field',
552  'joinVar' => 'field_join',
553  'conds' => [ 'alias' => 'text' ],
554  ],
555  "DELETE FROM table " .
556  "WHERE field IN (" .
557  "SELECT field_join FROM table_join WHERE alias = 'text'" .
558  ")"
559  ],
560  [
561  [
562  'delTable' => 'table',
563  'joinTable' => 'table_join',
564  'delVar' => 'field',
565  'joinVar' => 'field_join',
566  'conds' => '*',
567  ],
568  "DELETE FROM table " .
569  "WHERE field IN (" .
570  "SELECT field_join FROM table_join " .
571  ")"
572  ],
573  ];
574  }
575 
581  public function testInsert( $sql, $sqlText ) {
582  $this->database->insert(
583  $sql['table'],
584  $sql['rows'],
585  __METHOD__,
586  $sql['options'] ?? []
587  );
588  $this->assertLastSql( $sqlText );
589  }
590 
591  public static function provideInsert() {
592  return [
593  [
594  [
595  'table' => 'table',
596  'rows' => [ 'field' => 'text', 'field2' => 2 ],
597  ],
598  "INSERT INTO table " .
599  "(field,field2) " .
600  "VALUES ('text','2')"
601  ],
602  [
603  [
604  'table' => 'table',
605  'rows' => [ 'field' => 'text', 'field2' => 2 ],
606  'options' => 'IGNORE',
607  ],
608  "INSERT IGNORE INTO table " .
609  "(field,field2) " .
610  "VALUES ('text','2')"
611  ],
612  [
613  [
614  'table' => 'table',
615  'rows' => [
616  [ 'field' => 'text', 'field2' => 2 ],
617  [ 'field' => 'multi', 'field2' => 3 ],
618  ],
619  'options' => 'IGNORE',
620  ],
621  "INSERT IGNORE INTO table " .
622  "(field,field2) " .
623  "VALUES " .
624  "('text','2')," .
625  "('multi','3')"
626  ],
627  ];
628  }
629 
635  public function testInsertSelect( $sql, $sqlTextNative, $sqlSelect, $sqlInsert ) {
636  $this->database->insertSelect(
637  $sql['destTable'],
638  $sql['srcTable'],
639  $sql['varMap'],
640  $sql['conds'],
641  __METHOD__,
642  $sql['insertOptions'] ?? [],
643  $sql['selectOptions'] ?? [],
644  $sql['selectJoinConds'] ?? []
645  );
646  $this->assertLastSql( $sqlTextNative );
647 
648  $dbWeb = new DatabaseTestHelper( __CLASS__, [ 'cliMode' => false ] );
649  $dbWeb->forceNextResult( [
650  array_flip( array_keys( $sql['varMap'] ) )
651  ] );
652  $dbWeb->insertSelect(
653  $sql['destTable'],
654  $sql['srcTable'],
655  $sql['varMap'],
656  $sql['conds'],
657  __METHOD__,
658  $sql['insertOptions'] ?? [],
659  $sql['selectOptions'] ?? [],
660  $sql['selectJoinConds'] ?? []
661  );
662  $this->assertLastSqlDb( implode( '; ', [ $sqlSelect, 'BEGIN', $sqlInsert, 'COMMIT' ] ), $dbWeb );
663  }
664 
665  public static function provideInsertSelect() {
666  return [
667  [
668  [
669  'destTable' => 'insert_table',
670  'srcTable' => 'select_table',
671  'varMap' => [ 'field_insert' => 'field_select', 'field' => 'field2' ],
672  'conds' => '*',
673  ],
674  "INSERT INTO insert_table " .
675  "(field_insert,field) " .
676  "SELECT field_select,field2 " .
677  "FROM select_table",
678  "SELECT field_select AS field_insert,field2 AS field " .
679  "FROM select_table FOR UPDATE",
680  "INSERT INTO insert_table (field_insert,field) VALUES ('0','1')"
681  ],
682  [
683  [
684  'destTable' => 'insert_table',
685  'srcTable' => 'select_table',
686  'varMap' => [ 'field_insert' => 'field_select', 'field' => 'field2' ],
687  'conds' => [ 'field' => 2 ],
688  ],
689  "INSERT INTO insert_table " .
690  "(field_insert,field) " .
691  "SELECT field_select,field2 " .
692  "FROM select_table " .
693  "WHERE field = '2'",
694  "SELECT field_select AS field_insert,field2 AS field FROM " .
695  "select_table WHERE field = '2' FOR UPDATE",
696  "INSERT INTO insert_table (field_insert,field) VALUES ('0','1')"
697  ],
698  [
699  [
700  'destTable' => 'insert_table',
701  'srcTable' => 'select_table',
702  'varMap' => [ 'field_insert' => 'field_select', 'field' => 'field2' ],
703  'conds' => [ 'field' => 2 ],
704  'insertOptions' => 'IGNORE',
705  'selectOptions' => [ 'ORDER BY' => 'field' ],
706  ],
707  "INSERT IGNORE INTO insert_table " .
708  "(field_insert,field) " .
709  "SELECT field_select,field2 " .
710  "FROM select_table " .
711  "WHERE field = '2' " .
712  "ORDER BY field",
713  "SELECT field_select AS field_insert,field2 AS field " .
714  "FROM select_table WHERE field = '2' ORDER BY field FOR UPDATE",
715  "INSERT IGNORE INTO insert_table (field_insert,field) VALUES ('0','1')"
716  ],
717  [
718  [
719  'destTable' => 'insert_table',
720  'srcTable' => [ 'select_table1', 'select_table2' ],
721  'varMap' => [ 'field_insert' => 'field_select', 'field' => 'field2' ],
722  'conds' => [ 'field' => 2 ],
723  'insertOptions' => [ 'NO_AUTO_COLUMNS' ],
724  'selectOptions' => [ 'ORDER BY' => 'field', 'FORCE INDEX' => [ 'select_table1' => 'index1' ] ],
725  'selectJoinConds' => [
726  'select_table2' => [ 'LEFT JOIN', [ 'select_table1.foo = select_table2.bar' ] ],
727  ],
728  ],
729  "INSERT INTO insert_table " .
730  "(field_insert,field) " .
731  "SELECT field_select,field2 " .
732  "FROM select_table1 LEFT JOIN select_table2 ON ((select_table1.foo = select_table2.bar)) " .
733  "WHERE field = '2' " .
734  "ORDER BY field",
735  "SELECT field_select AS field_insert,field2 AS field " .
736  "FROM select_table1 LEFT JOIN select_table2 ON ((select_table1.foo = select_table2.bar)) " .
737  "WHERE field = '2' ORDER BY field FOR UPDATE",
738  "INSERT INTO insert_table (field_insert,field) VALUES ('0','1')"
739  ],
740  ];
741  }
742 
747  public function testInsertSelectBatching() {
748  $dbWeb = new DatabaseTestHelper( __CLASS__, [ 'cliMode' => false ] );
749  $rows = [];
750  for ( $i = 0; $i <= 25000; $i++ ) {
751  $rows[] = [ 'field' => $i ];
752  }
753  $dbWeb->forceNextResult( $rows );
754  $dbWeb->insertSelect(
755  'insert_table',
756  'select_table',
757  [ 'field' => 'field2' ],
758  '*',
759  __METHOD__
760  );
761  $this->assertLastSqlDb( implode( '; ', [
762  'SELECT field2 AS field FROM select_table FOR UPDATE',
763  'BEGIN',
764  "INSERT INTO insert_table (field) VALUES ('" . implode( "'),('", range( 0, 9999 ) ) . "')",
765  "INSERT INTO insert_table (field) VALUES ('" . implode( "'),('", range( 10000, 19999 ) ) . "')",
766  "INSERT INTO insert_table (field) VALUES ('" . implode( "'),('", range( 20000, 25000 ) ) . "')",
767  'COMMIT'
768  ] ), $dbWeb );
769  }
770 
775  public function testReplace( $sql, $sqlText ) {
776  $this->database->replace(
777  $sql['table'],
778  $sql['uniqueIndexes'],
779  $sql['rows'],
780  __METHOD__
781  );
782  $this->assertLastSql( $sqlText );
783  }
784 
785  public static function provideReplace() {
786  return [
787  [
788  [
789  'table' => 'replace_table',
790  'uniqueIndexes' => [ 'field' ],
791  'rows' => [ 'field' => 'text', 'field2' => 'text2' ],
792  ],
793  "BEGIN; DELETE FROM replace_table " .
794  "WHERE (field = 'text'); " .
795  "INSERT INTO replace_table " .
796  "(field,field2) " .
797  "VALUES ('text','text2'); COMMIT"
798  ],
799  [
800  [
801  'table' => 'module_deps',
802  'uniqueIndexes' => [ [ 'md_module', 'md_skin' ] ],
803  'rows' => [
804  'md_module' => 'module',
805  'md_skin' => 'skin',
806  'md_deps' => 'deps',
807  ],
808  ],
809  "BEGIN; DELETE FROM module_deps " .
810  "WHERE (md_module = 'module' AND md_skin = 'skin'); " .
811  "INSERT INTO module_deps " .
812  "(md_module,md_skin,md_deps) " .
813  "VALUES ('module','skin','deps'); COMMIT"
814  ],
815  [
816  [
817  'table' => 'module_deps',
818  'uniqueIndexes' => [ [ 'md_module', 'md_skin' ] ],
819  'rows' => [
820  [
821  'md_module' => 'module',
822  'md_skin' => 'skin',
823  'md_deps' => 'deps',
824  ], [
825  'md_module' => 'module2',
826  'md_skin' => 'skin2',
827  'md_deps' => 'deps2',
828  ],
829  ],
830  ],
831  "BEGIN; DELETE FROM module_deps " .
832  "WHERE (md_module = 'module' AND md_skin = 'skin'); " .
833  "INSERT INTO module_deps " .
834  "(md_module,md_skin,md_deps) " .
835  "VALUES ('module','skin','deps'); " .
836  "DELETE FROM module_deps " .
837  "WHERE (md_module = 'module2' AND md_skin = 'skin2'); " .
838  "INSERT INTO module_deps " .
839  "(md_module,md_skin,md_deps) " .
840  "VALUES ('module2','skin2','deps2'); COMMIT"
841  ],
842  [
843  [
844  'table' => 'module_deps',
845  'uniqueIndexes' => [ 'md_module', 'md_skin' ],
846  'rows' => [
847  [
848  'md_module' => 'module',
849  'md_skin' => 'skin',
850  'md_deps' => 'deps',
851  ], [
852  'md_module' => 'module2',
853  'md_skin' => 'skin2',
854  'md_deps' => 'deps2',
855  ],
856  ],
857  ],
858  "BEGIN; DELETE FROM module_deps " .
859  "WHERE (md_module = 'module') OR (md_skin = 'skin'); " .
860  "INSERT INTO module_deps " .
861  "(md_module,md_skin,md_deps) " .
862  "VALUES ('module','skin','deps'); " .
863  "DELETE FROM module_deps " .
864  "WHERE (md_module = 'module2') OR (md_skin = 'skin2'); " .
865  "INSERT INTO module_deps " .
866  "(md_module,md_skin,md_deps) " .
867  "VALUES ('module2','skin2','deps2'); COMMIT"
868  ],
869  [
870  [
871  'table' => 'module_deps',
872  'uniqueIndexes' => [],
873  'rows' => [
874  'md_module' => 'module',
875  'md_skin' => 'skin',
876  'md_deps' => 'deps',
877  ],
878  ],
879  "BEGIN; INSERT INTO module_deps " .
880  "(md_module,md_skin,md_deps) " .
881  "VALUES ('module','skin','deps'); COMMIT"
882  ],
883  ];
884  }
885 
890  public function testNativeReplace( $sql, $sqlText ) {
891  $this->database->nativeReplace(
892  $sql['table'],
893  $sql['rows'],
894  __METHOD__
895  );
896  $this->assertLastSql( $sqlText );
897  }
898 
899  public static function provideNativeReplace() {
900  return [
901  [
902  [
903  'table' => 'replace_table',
904  'rows' => [ 'field' => 'text', 'field2' => 'text2' ],
905  ],
906  "REPLACE INTO replace_table " .
907  "(field,field2) " .
908  "VALUES ('text','text2')"
909  ],
910  ];
911  }
912 
917  public function testConditional( $sql, $sqlText ) {
918  $this->assertEquals( trim( $this->database->conditional(
919  $sql['conds'],
920  $sql['true'],
921  $sql['false']
922  ) ), $sqlText );
923  }
924 
925  public static function provideConditional() {
926  return [
927  [
928  [
929  'conds' => [ 'field' => 'text' ],
930  'true' => 1,
931  'false' => 'NULL',
932  ],
933  "(CASE WHEN field = 'text' THEN 1 ELSE NULL END)"
934  ],
935  [
936  [
937  'conds' => [ 'field' => 'text', 'field2' => 'anothertext' ],
938  'true' => 1,
939  'false' => 'NULL',
940  ],
941  "(CASE WHEN field = 'text' AND field2 = 'anothertext' THEN 1 ELSE NULL END)"
942  ],
943  [
944  [
945  'conds' => 'field=1',
946  'true' => 1,
947  'false' => 'NULL',
948  ],
949  "(CASE WHEN field=1 THEN 1 ELSE NULL END)"
950  ],
951  ];
952  }
953 
958  public function testBuildConcat( $stringList, $sqlText ) {
959  $this->assertEquals( trim( $this->database->buildConcat(
960  $stringList
961  ) ), $sqlText );
962  }
963 
964  public static function provideBuildConcat() {
965  return [
966  [
967  [ 'field', 'field2' ],
968  "CONCAT(field,field2)"
969  ],
970  [
971  [ "'test'", 'field2' ],
972  "CONCAT('test',field2)"
973  ],
974  ];
975  }
976 
982  public function testBuildLike( $array, $sqlText ) {
983  $this->assertEquals( trim( $this->database->buildLike(
984  $array
985  ) ), $sqlText );
986  }
987 
988  public static function provideBuildLike() {
989  return [
990  [
991  'text',
992  "LIKE 'text' ESCAPE '`'"
993  ],
994  [
995  [ 'text', new LikeMatch( '%' ) ],
996  "LIKE 'text%' ESCAPE '`'"
997  ],
998  [
999  [ 'text', new LikeMatch( '%' ), 'text2' ],
1000  "LIKE 'text%text2' ESCAPE '`'"
1001  ],
1002  [
1003  [ 'text', new LikeMatch( '_' ) ],
1004  "LIKE 'text_' ESCAPE '`'"
1005  ],
1006  [
1007  'more_text',
1008  "LIKE 'more`_text' ESCAPE '`'"
1009  ],
1010  [
1011  [ 'C:\\Windows\\', new LikeMatch( '%' ) ],
1012  "LIKE 'C:\\Windows\\%' ESCAPE '`'"
1013  ],
1014  [
1015  [ 'accent`_test`', new LikeMatch( '%' ) ],
1016  "LIKE 'accent```_test``%' ESCAPE '`'"
1017  ],
1018  ];
1019  }
1020 
1025  public function testUnionQueries( $sql, $sqlText ) {
1026  $this->assertEquals( trim( $this->database->unionQueries(
1027  $sql['sqls'],
1028  $sql['all']
1029  ) ), $sqlText );
1030  }
1031 
1032  public static function provideUnionQueries() {
1033  return [
1034  [
1035  [
1036  'sqls' => [ 'RAW SQL', 'RAW2SQL' ],
1037  'all' => true,
1038  ],
1039  "(RAW SQL) UNION ALL (RAW2SQL)"
1040  ],
1041  [
1042  [
1043  'sqls' => [ 'RAW SQL', 'RAW2SQL' ],
1044  'all' => false,
1045  ],
1046  "(RAW SQL) UNION (RAW2SQL)"
1047  ],
1048  [
1049  [
1050  'sqls' => [ 'RAW SQL', 'RAW2SQL', 'RAW3SQL' ],
1051  'all' => false,
1052  ],
1053  "(RAW SQL) UNION (RAW2SQL) UNION (RAW3SQL)"
1054  ],
1055  ];
1056  }
1057 
1062  public function testUnionConditionPermutations( $params, $expect ) {
1063  if ( isset( $params['unionSupportsOrderAndLimit'] ) ) {
1064  $this->database->setUnionSupportsOrderAndLimit( $params['unionSupportsOrderAndLimit'] );
1065  }
1066 
1067  $sql = trim( $this->database->unionConditionPermutations(
1068  $params['table'],
1069  $params['vars'],
1070  $params['permute_conds'],
1071  $params['extra_conds'] ?? '',
1072  'FNAME',
1073  $params['options'] ?? [],
1074  $params['join_conds'] ?? []
1075  ) );
1076  $this->assertEquals( $expect, $sql );
1077  }
1078 
1079  public static function provideUnionConditionPermutations() {
1080  // phpcs:disable Generic.Files.LineLength
1081  return [
1082  [
1083  [
1084  'table' => [ 'table1', 'table2' ],
1085  'vars' => [ 'field1', 'alias' => 'field2' ],
1086  'permute_conds' => [
1087  'field3' => [ 1, 2, 3 ],
1088  'duplicates' => [ 4, 5, 4 ],
1089  'empty' => [],
1090  'single' => [ 0 ],
1091  ],
1092  'extra_conds' => 'table2.bar > 23',
1093  'options' => [
1094  'ORDER BY' => [ 'field1', 'alias' ],
1095  'INNER ORDER BY' => [ 'field1', 'field2' ],
1096  'LIMIT' => 100,
1097  ],
1098  'join_conds' => [
1099  'table2' => [ 'JOIN', 'table1.foo_id = table2.foo_id' ],
1100  ],
1101  ],
1102  "(SELECT field1,field2 AS alias FROM table1 JOIN table2 ON ((table1.foo_id = table2.foo_id)) WHERE field3 = '1' AND duplicates = '4' AND single = '0' AND (table2.bar > 23) ORDER BY field1,field2 LIMIT 100 ) UNION ALL " .
1103  "(SELECT field1,field2 AS alias FROM table1 JOIN table2 ON ((table1.foo_id = table2.foo_id)) WHERE field3 = '1' AND duplicates = '5' AND single = '0' AND (table2.bar > 23) ORDER BY field1,field2 LIMIT 100 ) UNION ALL " .
1104  "(SELECT field1,field2 AS alias FROM table1 JOIN table2 ON ((table1.foo_id = table2.foo_id)) WHERE field3 = '2' AND duplicates = '4' AND single = '0' AND (table2.bar > 23) ORDER BY field1,field2 LIMIT 100 ) UNION ALL " .
1105  "(SELECT field1,field2 AS alias FROM table1 JOIN table2 ON ((table1.foo_id = table2.foo_id)) WHERE field3 = '2' AND duplicates = '5' AND single = '0' AND (table2.bar > 23) ORDER BY field1,field2 LIMIT 100 ) UNION ALL " .
1106  "(SELECT field1,field2 AS alias FROM table1 JOIN table2 ON ((table1.foo_id = table2.foo_id)) WHERE field3 = '3' AND duplicates = '4' AND single = '0' AND (table2.bar > 23) ORDER BY field1,field2 LIMIT 100 ) UNION ALL " .
1107  "(SELECT field1,field2 AS alias FROM table1 JOIN table2 ON ((table1.foo_id = table2.foo_id)) WHERE field3 = '3' AND duplicates = '5' AND single = '0' AND (table2.bar > 23) ORDER BY field1,field2 LIMIT 100 ) " .
1108  "ORDER BY field1,alias LIMIT 100"
1109  ],
1110  [
1111  [
1112  'table' => 'foo',
1113  'vars' => [ 'foo_id' ],
1114  'permute_conds' => [
1115  'bar' => [ 1, 2, 3 ],
1116  ],
1117  'extra_conds' => [ 'baz' => null ],
1118  'options' => [
1119  'NOTALL',
1120  'ORDER BY' => [ 'foo_id' ],
1121  'LIMIT' => 25,
1122  ],
1123  ],
1124  "(SELECT foo_id FROM foo WHERE bar = '1' AND baz IS NULL ORDER BY foo_id LIMIT 25 ) UNION " .
1125  "(SELECT foo_id FROM foo WHERE bar = '2' AND baz IS NULL ORDER BY foo_id LIMIT 25 ) UNION " .
1126  "(SELECT foo_id FROM foo WHERE bar = '3' AND baz IS NULL ORDER BY foo_id LIMIT 25 ) " .
1127  "ORDER BY foo_id LIMIT 25"
1128  ],
1129  [
1130  [
1131  'table' => 'foo',
1132  'vars' => [ 'foo_id' ],
1133  'permute_conds' => [
1134  'bar' => [ 1, 2, 3 ],
1135  ],
1136  'extra_conds' => [ 'baz' => null ],
1137  'options' => [
1138  'NOTALL' => true,
1139  'ORDER BY' => [ 'foo_id' ],
1140  'LIMIT' => 25,
1141  ],
1142  'unionSupportsOrderAndLimit' => false,
1143  ],
1144  "(SELECT foo_id FROM foo WHERE bar = '1' AND baz IS NULL ) UNION " .
1145  "(SELECT foo_id FROM foo WHERE bar = '2' AND baz IS NULL ) UNION " .
1146  "(SELECT foo_id FROM foo WHERE bar = '3' AND baz IS NULL ) " .
1147  "ORDER BY foo_id LIMIT 25"
1148  ],
1149  [
1150  [
1151  'table' => 'foo',
1152  'vars' => [ 'foo_id' ],
1153  'permute_conds' => [],
1154  'extra_conds' => [ 'baz' => null ],
1155  'options' => [
1156  'ORDER BY' => [ 'foo_id' ],
1157  'LIMIT' => 25,
1158  ],
1159  ],
1160  "SELECT foo_id FROM foo WHERE baz IS NULL ORDER BY foo_id LIMIT 25"
1161  ],
1162  [
1163  [
1164  'table' => 'foo',
1165  'vars' => [ 'foo_id' ],
1166  'permute_conds' => [
1167  'bar' => [],
1168  ],
1169  'extra_conds' => [ 'baz' => null ],
1170  'options' => [
1171  'ORDER BY' => [ 'foo_id' ],
1172  'LIMIT' => 25,
1173  ],
1174  ],
1175  "SELECT foo_id FROM foo WHERE baz IS NULL ORDER BY foo_id LIMIT 25"
1176  ],
1177  [
1178  [
1179  'table' => 'foo',
1180  'vars' => [ 'foo_id' ],
1181  'permute_conds' => [
1182  'bar' => [ 1 ],
1183  ],
1184  'options' => [
1185  'ORDER BY' => [ 'foo_id' ],
1186  'LIMIT' => 25,
1187  'OFFSET' => 150,
1188  ],
1189  ],
1190  "SELECT foo_id FROM foo WHERE bar = '1' ORDER BY foo_id LIMIT 150,25"
1191  ],
1192  [
1193  [
1194  'table' => 'foo',
1195  'vars' => [ 'foo_id' ],
1196  'permute_conds' => [],
1197  'extra_conds' => [ 'baz' => null ],
1198  'options' => [
1199  'ORDER BY' => [ 'foo_id' ],
1200  'LIMIT' => 25,
1201  'OFFSET' => 150,
1202  'INNER ORDER BY' => [ 'bar_id' ],
1203  ],
1204  ],
1205  "(SELECT foo_id FROM foo WHERE baz IS NULL ORDER BY bar_id LIMIT 175 ) ORDER BY foo_id LIMIT 150,25"
1206  ],
1207  [
1208  [
1209  'table' => 'foo',
1210  'vars' => [ 'foo_id' ],
1211  'permute_conds' => [],
1212  'extra_conds' => [ 'baz' => null ],
1213  'options' => [
1214  'ORDER BY' => [ 'foo_id' ],
1215  'LIMIT' => 25,
1216  'OFFSET' => 150,
1217  'INNER ORDER BY' => [ 'bar_id' ],
1218  ],
1219  'unionSupportsOrderAndLimit' => false,
1220  ],
1221  "SELECT foo_id FROM foo WHERE baz IS NULL ORDER BY foo_id LIMIT 150,25"
1222  ],
1223  ];
1224  // phpcs:enable
1225  }
1226 
1231  public function testTransactionCommit() {
1232  $this->database->begin( __METHOD__ );
1233  $this->database->commit( __METHOD__ );
1234  $this->assertLastSql( 'BEGIN; COMMIT' );
1235  }
1236 
1241  public function testTransactionRollback() {
1242  $this->database->begin( __METHOD__ );
1243  $this->database->rollback( __METHOD__ );
1244  $this->assertLastSql( 'BEGIN; ROLLBACK' );
1245  }
1246 
1250  public function testDropTable() {
1251  $this->database->setExistingTables( [ 'table' ] );
1252  $this->database->dropTable( 'table', __METHOD__ );
1253  $this->assertLastSql( 'DROP TABLE table CASCADE' );
1254  }
1255 
1259  public function testDropNonExistingTable() {
1260  $this->assertFalse(
1261  $this->database->dropTable( 'non_existing', __METHOD__ )
1262  );
1263  }
1264 
1269  public function testMakeList( $list, $mode, $sqlText ) {
1270  $this->assertEquals( trim( $this->database->makeList(
1271  $list, $mode
1272  ) ), $sqlText );
1273  }
1274 
1275  public static function provideMakeList() {
1276  return [
1277  [
1278  [ 'value', 'value2' ],
1279  LIST_COMMA,
1280  "'value','value2'"
1281  ],
1282  [
1283  [ 'field', 'field2' ],
1284  LIST_NAMES,
1285  "field,field2"
1286  ],
1287  [
1288  [ 'field' => 'value', 'field2' => 'value2' ],
1289  LIST_AND,
1290  "field = 'value' AND field2 = 'value2'"
1291  ],
1292  [
1293  [ 'field' => null, "field2 != 'value2'" ],
1294  LIST_AND,
1295  "field IS NULL AND (field2 != 'value2')"
1296  ],
1297  [
1298  [ 'field' => [ 'value', null, 'value2' ], 'field2' => 'value2' ],
1299  LIST_AND,
1300  "(field IN ('value','value2') OR field IS NULL) AND field2 = 'value2'"
1301  ],
1302  [
1303  [ 'field' => [ null ], 'field2' => null ],
1304  LIST_AND,
1305  "field IS NULL AND field2 IS NULL"
1306  ],
1307  [
1308  [ 'field' => 'value', 'field2' => 'value2' ],
1309  LIST_OR,
1310  "field = 'value' OR field2 = 'value2'"
1311  ],
1312  [
1313  [ 'field' => 'value', 'field2' => null ],
1314  LIST_OR,
1315  "field = 'value' OR field2 IS NULL"
1316  ],
1317  [
1318  [ 'field' => [ 'value', 'value2' ], 'field2' => [ 'value' ] ],
1319  LIST_OR,
1320  "field IN ('value','value2') OR field2 = 'value'"
1321  ],
1322  [
1323  [ 'field' => [ null, 'value', null, 'value2' ], "field2 != 'value2'" ],
1324  LIST_OR,
1325  "(field IN ('value','value2') OR field IS NULL) OR (field2 != 'value2')"
1326  ],
1327  [
1328  [ 'field' => 'value', 'field2' => 'value2' ],
1329  LIST_SET,
1330  "field = 'value',field2 = 'value2'"
1331  ],
1332  [
1333  [ 'field' => 'value', 'field2' => null ],
1334  LIST_SET,
1335  "field = 'value',field2 = NULL"
1336  ],
1337  [
1338  [ 'field' => 'value', "field2 != 'value2'" ],
1339  LIST_SET,
1340  "field = 'value',field2 != 'value2'"
1341  ],
1342  ];
1343  }
1344 
1348  public function testSessionTempTables() {
1349  $temp1 = $this->database->tableName( 'tmp_table_1' );
1350  $temp2 = $this->database->tableName( 'tmp_table_2' );
1351  $temp3 = $this->database->tableName( 'tmp_table_3' );
1352 
1353  $this->database->query( "CREATE TEMPORARY TABLE $temp1 LIKE orig_tbl", __METHOD__ );
1354  $this->database->query( "CREATE TEMPORARY TABLE $temp2 LIKE orig_tbl", __METHOD__ );
1355  $this->database->query( "CREATE TEMPORARY TABLE $temp3 LIKE orig_tbl", __METHOD__ );
1356 
1357  $this->assertTrue( $this->database->tableExists( "tmp_table_1", __METHOD__ ) );
1358  $this->assertTrue( $this->database->tableExists( "tmp_table_2", __METHOD__ ) );
1359  $this->assertTrue( $this->database->tableExists( "tmp_table_3", __METHOD__ ) );
1360 
1361  $this->database->dropTable( 'tmp_table_1', __METHOD__ );
1362  $this->database->dropTable( 'tmp_table_2', __METHOD__ );
1363  $this->database->dropTable( 'tmp_table_3', __METHOD__ );
1364 
1365  $this->assertFalse( $this->database->tableExists( "tmp_table_1", __METHOD__ ) );
1366  $this->assertFalse( $this->database->tableExists( "tmp_table_2", __METHOD__ ) );
1367  $this->assertFalse( $this->database->tableExists( "tmp_table_3", __METHOD__ ) );
1368 
1369  $this->database->query( "CREATE TEMPORARY TABLE tmp_table_1 LIKE orig_tbl", __METHOD__ );
1370  $this->database->query( "CREATE TEMPORARY TABLE 'tmp_table_2' LIKE orig_tbl", __METHOD__ );
1371  $this->database->query( "CREATE TEMPORARY TABLE `tmp_table_3` LIKE orig_tbl", __METHOD__ );
1372 
1373  $this->assertTrue( $this->database->tableExists( "tmp_table_1", __METHOD__ ) );
1374  $this->assertTrue( $this->database->tableExists( "tmp_table_2", __METHOD__ ) );
1375  $this->assertTrue( $this->database->tableExists( "tmp_table_3", __METHOD__ ) );
1376 
1377  $this->database->query( "DROP TEMPORARY TABLE tmp_table_1 LIKE orig_tbl", __METHOD__ );
1378  $this->database->query( "DROP TEMPORARY TABLE 'tmp_table_2' LIKE orig_tbl", __METHOD__ );
1379  $this->database->query( "DROP TABLE `tmp_table_3` LIKE orig_tbl", __METHOD__ );
1380 
1381  $this->assertFalse( $this->database->tableExists( "tmp_table_1", __METHOD__ ) );
1382  $this->assertFalse( $this->database->tableExists( "tmp_table_2", __METHOD__ ) );
1383  $this->assertFalse( $this->database->tableExists( "tmp_table_3", __METHOD__ ) );
1384  }
1385 
1386  public function provideBuildSubstring() {
1387  yield [ 'someField', 1, 2, 'SUBSTRING(someField FROM 1 FOR 2)' ];
1388  yield [ 'someField', 1, null, 'SUBSTRING(someField FROM 1)' ];
1389  }
1390 
1395  public function testBuildSubstring( $input, $start, $length, $expected ) {
1396  $output = $this->database->buildSubstring( $input, $start, $length );
1397  $this->assertSame( $expected, $output );
1398  }
1399 
1401  yield [ -1, 1 ];
1402  yield [ 1, -1 ];
1403  yield [ 1, 'foo' ];
1404  yield [ 'foo', 1 ];
1405  yield [ null, 1 ];
1406  yield [ 0, 1 ];
1407  }
1408 
1414  public function testBuildSubstring_invalidParams( $start, $length ) {
1415  $this->setExpectedException( InvalidArgumentException::class );
1416  $this->database->buildSubstring( 'foo', $start, $length );
1417  }
1418 
1422  public function testBuildIntegerCast() {
1423  $output = $this->database->buildIntegerCast( 'fieldName' );
1424  $this->assertSame( 'CAST( fieldName AS INTEGER )', $output );
1425  }
1426 
1436  public function testAtomicSections() {
1437  $this->database->startAtomic( __METHOD__ );
1438  $this->database->endAtomic( __METHOD__ );
1439  $this->assertLastSql( 'BEGIN; COMMIT' );
1440 
1441  $this->database->startAtomic( __METHOD__, IDatabase::ATOMIC_CANCELABLE );
1442  $this->database->cancelAtomic( __METHOD__ );
1443  $this->assertLastSql( 'BEGIN; ROLLBACK' );
1444 
1445  $this->database->begin( __METHOD__ );
1446  $this->database->startAtomic( __METHOD__ );
1447  $this->database->endAtomic( __METHOD__ );
1448  $this->database->commit( __METHOD__ );
1449  $this->assertLastSql( 'BEGIN; COMMIT' );
1450 
1451  $this->database->begin( __METHOD__ );
1452  $this->database->startAtomic( __METHOD__, IDatabase::ATOMIC_CANCELABLE );
1453  $this->database->endAtomic( __METHOD__ );
1454  $this->database->commit( __METHOD__ );
1455  // phpcs:ignore Generic.Files.LineLength
1456  $this->assertLastSql( 'BEGIN; SAVEPOINT wikimedia_rdbms_atomic1; RELEASE SAVEPOINT wikimedia_rdbms_atomic1; COMMIT' );
1457 
1458  $this->database->begin( __METHOD__ );
1459  $this->database->startAtomic( __METHOD__, IDatabase::ATOMIC_CANCELABLE );
1460  $this->database->cancelAtomic( __METHOD__ );
1461  $this->database->commit( __METHOD__ );
1462  // phpcs:ignore Generic.Files.LineLength
1463  $this->assertLastSql( 'BEGIN; SAVEPOINT wikimedia_rdbms_atomic1; ROLLBACK TO SAVEPOINT wikimedia_rdbms_atomic1; COMMIT' );
1464 
1465  $this->database->startAtomic( __METHOD__, IDatabase::ATOMIC_CANCELABLE );
1466  $this->database->startAtomic( __METHOD__, IDatabase::ATOMIC_CANCELABLE );
1467  $this->database->cancelAtomic( __METHOD__ );
1468  $this->database->endAtomic( __METHOD__ );
1469  // phpcs:ignore Generic.Files.LineLength
1470  $this->assertLastSql( 'BEGIN; SAVEPOINT wikimedia_rdbms_atomic1; ROLLBACK TO SAVEPOINT wikimedia_rdbms_atomic1; COMMIT' );
1471 
1472  $noOpCallack = function () {
1473  };
1474 
1475  $this->database->doAtomicSection( __METHOD__, $noOpCallack, IDatabase::ATOMIC_CANCELABLE );
1476  $this->assertLastSql( 'BEGIN; COMMIT' );
1477 
1478  $this->database->doAtomicSection( __METHOD__, $noOpCallack );
1479  $this->assertLastSql( 'BEGIN; COMMIT' );
1480 
1481  $this->database->begin( __METHOD__ );
1482  $this->database->doAtomicSection( __METHOD__, $noOpCallack, IDatabase::ATOMIC_CANCELABLE );
1483  $this->database->rollback( __METHOD__ );
1484  // phpcs:ignore Generic.Files.LineLength
1485  $this->assertLastSql( 'BEGIN; SAVEPOINT wikimedia_rdbms_atomic1; RELEASE SAVEPOINT wikimedia_rdbms_atomic1; ROLLBACK' );
1486 
1487  $fname = __METHOD__;
1488  $triggerMap = [
1489  '-' => '-',
1490  IDatabase::TRIGGER_COMMIT => 'tCommit',
1491  IDatabase::TRIGGER_ROLLBACK => 'tRollback'
1492  ];
1493  $pcCallback = function ( IDatabase $db ) use ( $fname ) {
1494  $this->database->query( "SELECT 0", $fname );
1495  };
1496  $callback1 = function ( $trigger = '-' ) use ( $fname, $triggerMap ) {
1497  $this->database->query( "SELECT 1, {$triggerMap[$trigger]} AS t", $fname );
1498  };
1499  $callback2 = function ( $trigger = '-' ) use ( $fname, $triggerMap ) {
1500  $this->database->query( "SELECT 2, {$triggerMap[$trigger]} AS t", $fname );
1501  };
1502  $callback3 = function ( $trigger = '-' ) use ( $fname, $triggerMap ) {
1503  $this->database->query( "SELECT 3, {$triggerMap[$trigger]} AS t", $fname );
1504  };
1505 
1506  $this->database->startAtomic( __METHOD__, IDatabase::ATOMIC_CANCELABLE );
1507  $this->database->onTransactionPreCommitOrIdle( $pcCallback, __METHOD__ );
1508  $this->database->cancelAtomic( __METHOD__ );
1509  $this->assertLastSql( 'BEGIN; ROLLBACK' );
1510 
1511  $this->database->startAtomic( __METHOD__, IDatabase::ATOMIC_CANCELABLE );
1512  $this->database->onTransactionCommitOrIdle( $callback1, __METHOD__ );
1513  $this->database->cancelAtomic( __METHOD__ );
1514  $this->assertLastSql( 'BEGIN; ROLLBACK' );
1515 
1516  $this->database->startAtomic( __METHOD__, IDatabase::ATOMIC_CANCELABLE );
1517  $this->database->onTransactionResolution( $callback1, __METHOD__ );
1518  $this->database->cancelAtomic( __METHOD__ );
1519  $this->assertLastSql( 'BEGIN; ROLLBACK; SELECT 1, tRollback AS t' );
1520 
1521  $this->database->startAtomic( __METHOD__ . '_outer' );
1522  $this->database->onTransactionPreCommitOrIdle( $pcCallback, __METHOD__ );
1523  $this->database->startAtomic( __METHOD__, IDatabase::ATOMIC_CANCELABLE );
1524  $this->database->onTransactionPreCommitOrIdle( $pcCallback, __METHOD__ );
1525  $this->database->cancelAtomic( __METHOD__ );
1526  $this->database->onTransactionPreCommitOrIdle( $pcCallback, __METHOD__ );
1527  $this->database->endAtomic( __METHOD__ . '_outer' );
1528  $this->assertLastSql( implode( "; ", [
1529  'BEGIN',
1530  'SAVEPOINT wikimedia_rdbms_atomic1',
1531  'ROLLBACK TO SAVEPOINT wikimedia_rdbms_atomic1',
1532  'SELECT 0',
1533  'SELECT 0',
1534  'COMMIT'
1535  ] ) );
1536 
1537  $this->database->startAtomic( __METHOD__ . '_outer' );
1538  $this->database->onTransactionCommitOrIdle( $callback1, __METHOD__ );
1539  $this->database->startAtomic( __METHOD__, IDatabase::ATOMIC_CANCELABLE );
1540  $this->database->onTransactionCommitOrIdle( $callback2, __METHOD__ );
1541  $this->database->cancelAtomic( __METHOD__ );
1542  $this->database->onTransactionCommitOrIdle( $callback3, __METHOD__ );
1543  $this->database->endAtomic( __METHOD__ . '_outer' );
1544  $this->assertLastSql( implode( "; ", [
1545  'BEGIN',
1546  'SAVEPOINT wikimedia_rdbms_atomic1',
1547  'ROLLBACK TO SAVEPOINT wikimedia_rdbms_atomic1',
1548  'COMMIT',
1549  'SELECT 1, tCommit AS t',
1550  'SELECT 3, tCommit AS t'
1551  ] ) );
1552 
1553  $this->database->startAtomic( __METHOD__ . '_outer' );
1554  $this->database->onTransactionResolution( $callback1, __METHOD__ );
1555  $this->database->startAtomic( __METHOD__, IDatabase::ATOMIC_CANCELABLE );
1556  $this->database->onTransactionResolution( $callback2, __METHOD__ );
1557  $this->database->cancelAtomic( __METHOD__ );
1558  $this->database->onTransactionResolution( $callback3, __METHOD__ );
1559  $this->database->endAtomic( __METHOD__ . '_outer' );
1560  $this->assertLastSql( implode( "; ", [
1561  'BEGIN',
1562  'SAVEPOINT wikimedia_rdbms_atomic1',
1563  'ROLLBACK TO SAVEPOINT wikimedia_rdbms_atomic1',
1564  'COMMIT',
1565  'SELECT 1, tCommit AS t',
1566  'SELECT 2, tRollback AS t',
1567  'SELECT 3, tCommit AS t'
1568  ] ) );
1569 
1570  $makeCallback = function ( $id ) use ( $fname, $triggerMap ) {
1571  return function ( $trigger = '-' ) use ( $id, $fname, $triggerMap ) {
1572  $this->database->query( "SELECT $id, {$triggerMap[$trigger]} AS t", $fname );
1573  };
1574  };
1575 
1576  $this->database->startAtomic( __METHOD__ . '_outer' );
1577  $this->database->startAtomic( __METHOD__, IDatabase::ATOMIC_CANCELABLE );
1578  $this->database->onTransactionResolution( $makeCallback( 1 ), __METHOD__ );
1579  $this->database->cancelAtomic( __METHOD__ );
1580  $this->database->endAtomic( __METHOD__ . '_outer' );
1581  $this->assertLastSql( implode( "; ", [
1582  'BEGIN',
1583  'SAVEPOINT wikimedia_rdbms_atomic1',
1584  'ROLLBACK TO SAVEPOINT wikimedia_rdbms_atomic1',
1585  'COMMIT',
1586  'SELECT 1, tRollback AS t'
1587  ] ) );
1588 
1589  $this->database->startAtomic( __METHOD__ . '_level1', IDatabase::ATOMIC_CANCELABLE );
1590  $this->database->onTransactionResolution( $makeCallback( 1 ), __METHOD__ );
1591  $this->database->startAtomic( __METHOD__ . '_level2' );
1592  $this->database->startAtomic( __METHOD__ . '_level3', IDatabase::ATOMIC_CANCELABLE );
1593  $this->database->startAtomic( __METHOD__, IDatabase::ATOMIC_CANCELABLE );
1594  $this->database->onTransactionResolution( $makeCallback( 2 ), __METHOD__ );
1595  $this->database->endAtomic( __METHOD__ );
1596  $this->database->onTransactionResolution( $makeCallback( 3 ), __METHOD__ );
1597  $this->database->cancelAtomic( __METHOD__ . '_level3' );
1598  $this->database->endAtomic( __METHOD__ . '_level2' );
1599  $this->database->onTransactionResolution( $makeCallback( 4 ), __METHOD__ );
1600  $this->database->endAtomic( __METHOD__ . '_level1' );
1601  $this->assertLastSql( implode( "; ", [
1602  'BEGIN',
1603  'SAVEPOINT wikimedia_rdbms_atomic1',
1604  'SAVEPOINT wikimedia_rdbms_atomic2',
1605  'RELEASE SAVEPOINT wikimedia_rdbms_atomic2',
1606  'ROLLBACK TO SAVEPOINT wikimedia_rdbms_atomic1',
1607  'COMMIT; SELECT 1, tCommit AS t',
1608  'SELECT 2, tRollback AS t',
1609  'SELECT 3, tRollback AS t',
1610  'SELECT 4, tCommit AS t'
1611  ] ) );
1612  }
1613 
1623  public function testAtomicSectionsRecovery() {
1624  $this->database->begin( __METHOD__ );
1625  try {
1626  $this->database->doAtomicSection(
1627  __METHOD__,
1628  function () {
1629  $this->database->startAtomic( 'inner_func1' );
1630  $this->database->startAtomic( 'inner_func2' );
1631 
1632  throw new RuntimeException( 'Test exception' );
1633  },
1634  IDatabase::ATOMIC_CANCELABLE
1635  );
1636  $this->fail( 'Expected exception not thrown' );
1637  } catch ( RuntimeException $ex ) {
1638  $this->assertSame( 'Test exception', $ex->getMessage() );
1639  }
1640  $this->database->commit( __METHOD__ );
1641  // phpcs:ignore Generic.Files.LineLength
1642  $this->assertLastSql( 'BEGIN; SAVEPOINT wikimedia_rdbms_atomic1; ROLLBACK TO SAVEPOINT wikimedia_rdbms_atomic1; COMMIT' );
1643 
1644  $this->database->begin( __METHOD__ );
1645  try {
1646  $this->database->doAtomicSection(
1647  __METHOD__,
1648  function () {
1649  throw new RuntimeException( 'Test exception' );
1650  }
1651  );
1652  $this->fail( 'Test exception not thrown' );
1653  } catch ( RuntimeException $ex ) {
1654  $this->assertSame( 'Test exception', $ex->getMessage() );
1655  }
1656  try {
1657  $this->database->commit( __METHOD__ );
1658  $this->fail( 'Test exception not thrown' );
1659  } catch ( DBTransactionError $ex ) {
1660  $this->assertSame(
1661  'Cannot execute query from ' . __METHOD__ . ' while transaction status is ERROR.',
1662  $ex->getMessage()
1663  );
1664  }
1665  $this->database->rollback( __METHOD__ );
1666  $this->assertLastSql( 'BEGIN; ROLLBACK' );
1667  }
1668 
1679  $fname = __METHOD__;
1680  $callback1Called = null;
1681  $callback1 = function ( $trigger = '-' ) use ( $fname, &$callback1Called ) {
1682  $callback1Called = $trigger;
1683  $this->database->query( "SELECT 1", $fname );
1684  };
1685  $callback2Called = null;
1686  $callback2 = function ( $trigger = '-' ) use ( $fname, &$callback2Called ) {
1687  $callback2Called = $trigger;
1688  $this->database->query( "SELECT 2", $fname );
1689  };
1690  $callback3Called = null;
1691  $callback3 = function ( $trigger = '-' ) use ( $fname, &$callback3Called ) {
1692  $callback3Called = $trigger;
1693  $this->database->query( "SELECT 3", $fname );
1694  };
1695 
1696  $this->database->startAtomic( __METHOD__ . '_outer' );
1697  $this->database->startAtomic( __METHOD__, IDatabase::ATOMIC_CANCELABLE );
1698  $this->database->startAtomic( __METHOD__ . '_inner' );
1699  $this->database->onTransactionCommitOrIdle( $callback1, __METHOD__ );
1700  $this->database->onTransactionPreCommitOrIdle( $callback2, __METHOD__ );
1701  $this->database->onTransactionResolution( $callback3, __METHOD__ );
1702  $this->database->endAtomic( __METHOD__ . '_inner' );
1703  $this->database->cancelAtomic( __METHOD__ );
1704  $this->database->endAtomic( __METHOD__ . '_outer' );
1705  $this->assertNull( $callback1Called );
1706  $this->assertNull( $callback2Called );
1707  $this->assertEquals( IDatabase::TRIGGER_ROLLBACK, $callback3Called );
1708  // phpcs:ignore Generic.Files.LineLength
1709  $this->assertLastSql( 'BEGIN; SAVEPOINT wikimedia_rdbms_atomic1; ROLLBACK TO SAVEPOINT wikimedia_rdbms_atomic1; COMMIT; SELECT 3' );
1710 
1711  $callback1Called = null;
1712  $callback2Called = null;
1713  $callback3Called = null;
1714  $this->database->startAtomic( __METHOD__ . '_outer' );
1715  $this->database->startAtomic( __METHOD__, IDatabase::ATOMIC_CANCELABLE );
1716  $this->database->startAtomic( __METHOD__ . '_inner', IDatabase::ATOMIC_CANCELABLE );
1717  $this->database->onTransactionCommitOrIdle( $callback1, __METHOD__ );
1718  $this->database->onTransactionPreCommitOrIdle( $callback2, __METHOD__ );
1719  $this->database->onTransactionResolution( $callback3, __METHOD__ );
1720  $this->database->endAtomic( __METHOD__ . '_inner' );
1721  $this->database->cancelAtomic( __METHOD__ );
1722  $this->database->endAtomic( __METHOD__ . '_outer' );
1723  $this->assertNull( $callback1Called );
1724  $this->assertNull( $callback2Called );
1725  $this->assertEquals( IDatabase::TRIGGER_ROLLBACK, $callback3Called );
1726  // phpcs:ignore Generic.Files.LineLength
1727  $this->assertLastSql( 'BEGIN; SAVEPOINT wikimedia_rdbms_atomic1; SAVEPOINT wikimedia_rdbms_atomic2; RELEASE SAVEPOINT wikimedia_rdbms_atomic2; ROLLBACK TO SAVEPOINT wikimedia_rdbms_atomic1; COMMIT; SELECT 3' );
1728 
1729  $callback1Called = null;
1730  $callback2Called = null;
1731  $callback3Called = null;
1732  $this->database->startAtomic( __METHOD__ . '_outer' );
1733  $atomicId = $this->database->startAtomic( __METHOD__, IDatabase::ATOMIC_CANCELABLE );
1734  $this->database->startAtomic( __METHOD__ . '_inner' );
1735  $this->database->onTransactionCommitOrIdle( $callback1, __METHOD__ );
1736  $this->database->onTransactionPreCommitOrIdle( $callback2, __METHOD__ );
1737  $this->database->onTransactionResolution( $callback3, __METHOD__ );
1738  $this->database->cancelAtomic( __METHOD__, $atomicId );
1739  $this->database->endAtomic( __METHOD__ . '_outer' );
1740  $this->assertNull( $callback1Called );
1741  $this->assertNull( $callback2Called );
1742  $this->assertEquals( IDatabase::TRIGGER_ROLLBACK, $callback3Called );
1743 
1744  $callback1Called = null;
1745  $callback2Called = null;
1746  $callback3Called = null;
1747  $this->database->startAtomic( __METHOD__ . '_outer' );
1748  $atomicId = $this->database->startAtomic( __METHOD__, IDatabase::ATOMIC_CANCELABLE );
1749  $this->database->startAtomic( __METHOD__ . '_inner' );
1750  $this->database->onTransactionCommitOrIdle( $callback1, __METHOD__ );
1751  $this->database->onTransactionPreCommitOrIdle( $callback2, __METHOD__ );
1752  $this->database->onTransactionResolution( $callback3, __METHOD__ );
1753  try {
1754  $this->database->cancelAtomic( __METHOD__ . '_X', $atomicId );
1755  } catch ( DBUnexpectedError $e ) {
1756  $m = __METHOD__;
1757  $this->assertSame(
1758  "Invalid atomic section ended (got {$m}_X but expected {$m}).",
1759  $e->getMessage()
1760  );
1761  }
1762  $this->database->cancelAtomic( __METHOD__ );
1763  $this->database->endAtomic( __METHOD__ . '_outer' );
1764  $this->assertNull( $callback1Called );
1765  $this->assertNull( $callback2Called );
1766  $this->assertEquals( IDatabase::TRIGGER_ROLLBACK, $callback3Called );
1767 
1768  $this->database->startAtomic( __METHOD__ . '_outer' );
1769  $this->database->startAtomic( __METHOD__, IDatabase::ATOMIC_CANCELABLE );
1770  $this->database->startAtomic( __METHOD__ . '_inner' );
1771  $this->database->onTransactionCommitOrIdle( $callback1, __METHOD__ );
1772  $this->database->onTransactionPreCommitOrIdle( $callback2, __METHOD__ );
1773  $this->database->onTransactionResolution( $callback3, __METHOD__ );
1774  $this->database->cancelAtomic( __METHOD__ . '_inner' );
1775  $this->database->cancelAtomic( __METHOD__ );
1776  $this->database->endAtomic( __METHOD__ . '_outer' );
1777  $this->assertNull( $callback1Called );
1778  $this->assertNull( $callback2Called );
1779  $this->assertEquals( IDatabase::TRIGGER_ROLLBACK, $callback3Called );
1780 
1781  $wrapper = TestingAccessWrapper::newFromObject( $this->database );
1782  $callback1Called = null;
1783  $callback2Called = null;
1784  $callback3Called = null;
1785  $this->database->startAtomic( __METHOD__ . '_outer' );
1786  $this->database->startAtomic( __METHOD__, IDatabase::ATOMIC_CANCELABLE );
1787  $this->database->startAtomic( __METHOD__ . '_inner' );
1788  $this->database->onTransactionCommitOrIdle( $callback1, __METHOD__ );
1789  $this->database->onTransactionPreCommitOrIdle( $callback2, __METHOD__ );
1790  $this->database->onTransactionResolution( $callback3, __METHOD__ );
1791  $wrapper->trxStatus = Database::STATUS_TRX_ERROR;
1792  $this->database->cancelAtomic( __METHOD__ . '_inner' );
1793  $this->database->cancelAtomic( __METHOD__ );
1794  $this->database->endAtomic( __METHOD__ . '_outer' );
1795  $this->assertNull( $callback1Called );
1796  $this->assertNull( $callback2Called );
1797  $this->assertEquals( IDatabase::TRIGGER_ROLLBACK, $callback3Called );
1798  }
1799 
1809  public function testAtomicSectionsTrxRound() {
1810  $this->database->setFlag( IDatabase::DBO_TRX );
1811  $this->database->startAtomic( __METHOD__, IDatabase::ATOMIC_CANCELABLE );
1812  $this->database->query( 'SELECT 1', __METHOD__ );
1813  $this->database->endAtomic( __METHOD__ );
1814  $this->database->commit( __METHOD__, IDatabase::FLUSHING_ALL_PEERS );
1815  // phpcs:ignore Generic.Files.LineLength
1816  $this->assertLastSql( 'BEGIN; SAVEPOINT wikimedia_rdbms_atomic1; SELECT 1; RELEASE SAVEPOINT wikimedia_rdbms_atomic1; COMMIT' );
1817  }
1818 
1819  public static function provideAtomicSectionMethodsForErrors() {
1820  return [
1821  [ 'endAtomic' ],
1822  [ 'cancelAtomic' ],
1823  ];
1824  }
1825 
1831  public function testNoAtomicSection( $method ) {
1832  try {
1833  $this->database->$method( __METHOD__ );
1834  $this->fail( 'Expected exception not thrown' );
1835  } catch ( DBUnexpectedError $ex ) {
1836  $this->assertSame(
1837  'No atomic section is open (got ' . __METHOD__ . ').',
1838  $ex->getMessage()
1839  );
1840  }
1841  }
1842 
1848  public function testInvalidAtomicSectionEnded( $method ) {
1849  $this->database->startAtomic( __METHOD__ . 'X' );
1850  try {
1851  $this->database->$method( __METHOD__ );
1852  $this->fail( 'Expected exception not thrown' );
1853  } catch ( DBUnexpectedError $ex ) {
1854  $this->assertSame(
1855  'Invalid atomic section ended (got ' . __METHOD__ . ' but expected ' .
1856  __METHOD__ . 'X).',
1857  $ex->getMessage()
1858  );
1859  }
1860  }
1861 
1866  $this->database->startAtomic( __METHOD__ );
1867  try {
1868  $this->database->cancelAtomic( __METHOD__ );
1869  $this->database->select( 'test', '1', [], __METHOD__ );
1870  $this->fail( 'Expected exception not thrown' );
1871  } catch ( DBTransactionError $ex ) {
1872  $this->assertSame(
1873  'Cannot execute query from ' . __METHOD__ . ' while transaction status is ERROR.',
1874  $ex->getMessage()
1875  );
1876  }
1877  }
1878 
1883  public function testTransactionErrorState1() {
1884  $wrapper = TestingAccessWrapper::newFromObject( $this->database );
1885 
1886  $this->database->begin( __METHOD__ );
1887  $wrapper->trxStatus = Database::STATUS_TRX_ERROR;
1888  $this->database->delete( 'x', [ 'field' => 3 ], __METHOD__ );
1889  $this->database->commit( __METHOD__ );
1890  }
1891 
1895  public function testTransactionErrorState2() {
1896  $wrapper = TestingAccessWrapper::newFromObject( $this->database );
1897 
1898  $this->database->startAtomic( __METHOD__ );
1899  $wrapper->trxStatus = Database::STATUS_TRX_ERROR;
1900  $this->database->rollback( __METHOD__ );
1901  $this->assertEquals( 0, $this->database->trxLevel() );
1902  $this->assertEquals( Database::STATUS_TRX_NONE, $wrapper->trxStatus() );
1903  $this->assertLastSql( 'BEGIN; ROLLBACK' );
1904 
1905  $this->database->startAtomic( __METHOD__ );
1906  $this->assertEquals( Database::STATUS_TRX_OK, $wrapper->trxStatus() );
1907  $this->database->delete( 'x', [ 'field' => 1 ], __METHOD__ );
1908  $this->database->endAtomic( __METHOD__ );
1909  $this->assertEquals( Database::STATUS_TRX_NONE, $wrapper->trxStatus() );
1910  $this->assertLastSql( 'BEGIN; DELETE FROM x WHERE field = \'1\'; COMMIT' );
1911  $this->assertEquals( 0, $this->database->trxLevel(), 'Use after rollback()' );
1912 
1913  $this->database->begin( __METHOD__ );
1914  $this->database->startAtomic( __METHOD__, Database::ATOMIC_CANCELABLE );
1915  $this->database->update( 'y', [ 'a' => 1 ], [ 'field' => 1 ], __METHOD__ );
1916  $wrapper->trxStatus = Database::STATUS_TRX_ERROR;
1917  $this->database->cancelAtomic( __METHOD__ );
1918  $this->assertEquals( Database::STATUS_TRX_OK, $wrapper->trxStatus() );
1919  $this->database->startAtomic( __METHOD__ );
1920  $this->database->delete( 'y', [ 'field' => 1 ], __METHOD__ );
1921  $this->database->endAtomic( __METHOD__ );
1922  $this->database->commit( __METHOD__ );
1923  // phpcs:ignore Generic.Files.LineLength
1924  $this->assertLastSql( 'BEGIN; SAVEPOINT wikimedia_rdbms_atomic1; UPDATE y SET a = \'1\' WHERE field = \'1\'; ROLLBACK TO SAVEPOINT wikimedia_rdbms_atomic1; DELETE FROM y WHERE field = \'1\'; COMMIT' );
1925  $this->assertEquals( 0, $this->database->trxLevel(), 'Use after rollback()' );
1926 
1927  // Next transaction
1928  $this->database->startAtomic( __METHOD__ );
1929  $this->assertEquals( Database::STATUS_TRX_OK, $wrapper->trxStatus() );
1930  $this->database->delete( 'x', [ 'field' => 3 ], __METHOD__ );
1931  $this->database->endAtomic( __METHOD__ );
1932  $this->assertEquals( Database::STATUS_TRX_NONE, $wrapper->trxStatus() );
1933  $this->assertLastSql( 'BEGIN; DELETE FROM x WHERE field = \'3\'; COMMIT' );
1934  $this->assertEquals( 0, $this->database->trxLevel() );
1935  }
1936 
1941  $doError = function () {
1942  $this->database->forceNextQueryError( 666, 'Evilness' );
1943  try {
1944  $this->database->delete( 'error', '1', __CLASS__ . '::SomeCaller' );
1945  $this->fail( 'Expected exception not thrown' );
1946  } catch ( DBError $e ) {
1947  $this->assertSame( 666, $e->errno );
1948  }
1949  };
1950 
1951  $this->database->setFlag( Database::DBO_TRX );
1952 
1953  // Implicit transaction does not get silently rolled back
1954  $this->database->begin( __METHOD__, Database::TRANSACTION_INTERNAL );
1955  call_user_func( $doError );
1956  try {
1957  $this->database->delete( 'x', [ 'field' => 1 ], __METHOD__ );
1958  $this->fail( 'Expected exception not thrown' );
1959  } catch ( DBTransactionError $e ) {
1960  $this->assertEquals(
1961  'Cannot execute query from ' . __METHOD__ . ' while transaction status is ERROR.',
1962  $e->getMessage()
1963  );
1964  }
1965  try {
1966  $this->database->commit( __METHOD__, Database::FLUSHING_INTERNAL );
1967  $this->fail( 'Expected exception not thrown' );
1968  } catch ( DBTransactionError $e ) {
1969  $this->assertEquals(
1970  'Cannot execute query from ' . __METHOD__ . ' while transaction status is ERROR.',
1971  $e->getMessage()
1972  );
1973  }
1974  $this->database->rollback( __METHOD__, Database::FLUSHING_INTERNAL );
1975  $this->assertLastSql( 'BEGIN; DELETE FROM error WHERE 1; ROLLBACK' );
1976 
1977  // Likewise if there were prior writes
1978  $this->database->begin( __METHOD__, Database::TRANSACTION_INTERNAL );
1979  $this->database->delete( 'x', [ 'field' => 1 ], __METHOD__ );
1980  call_user_func( $doError );
1981  try {
1982  $this->database->delete( 'x', [ 'field' => 1 ], __METHOD__ );
1983  $this->fail( 'Expected exception not thrown' );
1984  } catch ( DBTransactionStateError $e ) {
1985  }
1986  $this->database->rollback( __METHOD__, Database::FLUSHING_INTERNAL );
1987  // phpcs:ignore
1988  $this->assertLastSql( 'BEGIN; DELETE FROM x WHERE field = \'1\'; DELETE FROM error WHERE 1; ROLLBACK' );
1989  }
1990 
1995  $wrapper = TestingAccessWrapper::newFromObject( $this->database );
1996  $warning = [];
1997  $wrapper->deprecationLogger = function ( $msg ) use ( &$warning ) {
1998  $warning[] = $msg;
1999  };
2000 
2001  $doError = function () {
2002  $this->database->forceNextQueryError( 666, 'Evilness', [
2003  'wasKnownStatementRollbackError' => true,
2004  ] );
2005  try {
2006  $this->database->delete( 'error', '1', __CLASS__ . '::SomeCaller' );
2007  $this->fail( 'Expected exception not thrown' );
2008  } catch ( DBError $e ) {
2009  $this->assertSame( 666, $e->errno );
2010  }
2011  };
2012  $expectWarning = 'Caller from ' . __METHOD__ .
2013  ' ignored an error originally raised from ' . __CLASS__ . '::SomeCaller: [666] Evilness';
2014 
2015  // Rollback doesn't raise a warning
2016  $warning = [];
2017  $this->database->startAtomic( __METHOD__ );
2018  call_user_func( $doError );
2019  $this->database->rollback( __METHOD__ );
2020  $this->database->delete( 'x', [ 'field' => 1 ], __METHOD__ );
2021  $this->assertSame( [], $warning );
2022  // phpcs:ignore
2023  $this->assertLastSql( 'BEGIN; DELETE FROM error WHERE 1; ROLLBACK; DELETE FROM x WHERE field = \'1\'' );
2024 
2025  // cancelAtomic() doesn't raise a warning
2026  $warning = [];
2027  $this->database->begin( __METHOD__ );
2028  $this->database->startAtomic( __METHOD__, Database::ATOMIC_CANCELABLE );
2029  call_user_func( $doError );
2030  $this->database->cancelAtomic( __METHOD__ );
2031  $this->database->delete( 'x', [ 'field' => 1 ], __METHOD__ );
2032  $this->database->commit( __METHOD__ );
2033  $this->assertSame( [], $warning );
2034  // phpcs:ignore
2035  $this->assertLastSql( 'BEGIN; SAVEPOINT wikimedia_rdbms_atomic1; DELETE FROM error WHERE 1; ROLLBACK TO SAVEPOINT wikimedia_rdbms_atomic1; DELETE FROM x WHERE field = \'1\'; COMMIT' );
2036 
2037  // Commit does raise a warning
2038  $warning = [];
2039  $this->database->begin( __METHOD__ );
2040  call_user_func( $doError );
2041  $this->database->commit( __METHOD__ );
2042  $this->assertSame( [ $expectWarning ], $warning );
2043  $this->assertLastSql( 'BEGIN; DELETE FROM error WHERE 1; COMMIT' );
2044 
2045  // Deprecation only gets raised once
2046  $warning = [];
2047  $this->database->begin( __METHOD__ );
2048  call_user_func( $doError );
2049  $this->database->delete( 'x', [ 'field' => 1 ], __METHOD__ );
2050  $this->database->commit( __METHOD__ );
2051  $this->assertSame( [ $expectWarning ], $warning );
2052  // phpcs:ignore
2053  $this->assertLastSql( 'BEGIN; DELETE FROM error WHERE 1; DELETE FROM x WHERE field = \'1\'; COMMIT' );
2054  }
2055 
2059  public function testPrematureClose1() {
2060  $fname = __METHOD__;
2061  $this->database->begin( __METHOD__ );
2062  $this->database->onTransactionCommitOrIdle( function () use ( $fname ) {
2063  $this->database->query( 'SELECT 1', $fname );
2064  } );
2065  $this->database->onTransactionResolution( function () use ( $fname ) {
2066  $this->database->query( 'SELECT 2', $fname );
2067  } );
2068  $this->database->delete( 'x', [ 'field' => 3 ], __METHOD__ );
2069  try {
2070  $this->database->close();
2071  $this->fail( 'Expected exception not thrown' );
2072  } catch ( DBUnexpectedError $ex ) {
2073  $this->assertSame(
2074  "Wikimedia\Rdbms\Database::close: transaction is still open (from $fname).",
2075  $ex->getMessage()
2076  );
2077  }
2078 
2079  $this->assertFalse( $this->database->isOpen() );
2080  $this->assertLastSql( 'BEGIN; DELETE FROM x WHERE field = \'3\'; ROLLBACK; SELECT 2' );
2081  $this->assertEquals( 0, $this->database->trxLevel() );
2082  }
2083 
2087  public function testPrematureClose2() {
2088  try {
2089  $fname = __METHOD__;
2090  $this->database->startAtomic( __METHOD__ );
2091  $this->database->onTransactionCommitOrIdle( function () use ( $fname ) {
2092  $this->database->query( 'SELECT 1', $fname );
2093  } );
2094  $this->database->delete( 'x', [ 'field' => 3 ], __METHOD__ );
2095  $this->database->close();
2096  $this->fail( 'Expected exception not thrown' );
2097  } catch ( DBUnexpectedError $ex ) {
2098  $this->assertSame(
2099  'Wikimedia\Rdbms\Database::close: atomic sections ' .
2100  'DatabaseSQLTest::testPrematureClose2 are still open.',
2101  $ex->getMessage()
2102  );
2103  }
2104 
2105  $this->assertFalse( $this->database->isOpen() );
2106  $this->assertLastSql( 'BEGIN; DELETE FROM x WHERE field = \'3\'; ROLLBACK' );
2107  $this->assertEquals( 0, $this->database->trxLevel() );
2108  }
2109 
2113  public function testPrematureClose3() {
2114  try {
2115  $this->database->setFlag( IDatabase::DBO_TRX );
2116  $this->database->delete( 'x', [ 'field' => 3 ], __METHOD__ );
2117  $this->assertEquals( 1, $this->database->trxLevel() );
2118  $this->database->close();
2119  $this->fail( 'Expected exception not thrown' );
2120  } catch ( DBUnexpectedError $ex ) {
2121  $this->assertSame(
2122  'Wikimedia\Rdbms\Database::close: ' .
2123  'mass commit/rollback of peer transaction required (DBO_TRX set).',
2124  $ex->getMessage()
2125  );
2126  }
2127 
2128  $this->assertFalse( $this->database->isOpen() );
2129  $this->assertLastSql( 'BEGIN; DELETE FROM x WHERE field = \'3\'; ROLLBACK' );
2130  $this->assertEquals( 0, $this->database->trxLevel() );
2131  }
2132 
2136  public function testPrematureClose4() {
2137  $this->database->setFlag( IDatabase::DBO_TRX );
2138  $this->database->query( 'SELECT 1', __METHOD__ );
2139  $this->assertEquals( 1, $this->database->trxLevel() );
2140  $this->database->close();
2141  $this->database->clearFlag( IDatabase::DBO_TRX );
2142 
2143  $this->assertFalse( $this->database->isOpen() );
2144  $this->assertLastSql( 'BEGIN; SELECT 1; ROLLBACK' );
2145  $this->assertEquals( 0, $this->database->trxLevel() );
2146  }
2147 
2151  public function testSelectFieldValues() {
2152  $this->database->forceNextResult( [
2153  (object)[ 'value' => 'row1' ],
2154  (object)[ 'value' => 'row2' ],
2155  (object)[ 'value' => 'row3' ],
2156  ] );
2157 
2158  $this->assertSame(
2159  [ 'row1', 'row2', 'row3' ],
2160  $this->database->selectFieldValues( 'table', 'table.field', 'conds', __METHOD__ )
2161  );
2162  $this->assertLastSql( 'SELECT table.field AS value FROM table WHERE conds' );
2163  }
2164 }
testSelect( $sql, $sqlText)
provideSelect Wikimedia\Rdbms\Database::select Wikimedia\Rdbms\Database::selectSQLText Wikimedia\Rdbm...
testAtomicSections()
\Wikimedia\Rdbms\Database::doSavepoint \Wikimedia\Rdbms\Database::doReleaseSavepoint \Wikimedia\Rdbms...
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction $rows
Definition: hooks.txt:2633
static provideUnionConditionPermutations()
testTransactionStatementRollbackIgnoring()
\Wikimedia\Rdbms\Database::query
if(is_array( $mode)) switch( $mode) $input
testMakeList( $list, $mode, $sqlText)
provideMakeList Wikimedia\Rdbms\Database::makeList
testSessionTempTables()
Wikimedia\Rdbms\Database::registerTempTableWrite.
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
testTransactionCommit()
Wikimedia\Rdbms\Database::commit Wikimedia\Rdbms\Database::doCommit.
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2159
const LIST_NAMES
Definition: Defines.php:45
static provideSelectRowCount()
testUpdate( $sql, $sqlText)
provideUpdate Wikimedia\Rdbms\Database::update Wikimedia\Rdbms\Database::makeUpdateOptions Wikimedia\...
static provideBuildConcat()
testBuildIntegerCast()
\Wikimedia\Rdbms\Database::buildIntegerCast
static provideUnionQueries()
testTransactionRollback()
Wikimedia\Rdbms\Database::rollback Wikimedia\Rdbms\Database::doRollback.
testNativeReplace( $sql, $sqlText)
provideNativeReplace Wikimedia\Rdbms\Database::nativeReplace
testPrematureClose4()
\Wikimedia\Rdbms\Database::close
static provideInsertSelect()
testPrematureClose1()
\Wikimedia\Rdbms\Database::close
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title e g db for database replication lag or jobqueue for job queue size converted to pseudo seconds It is possible to add more fields and they will be returned to the user in the API response after the basic globals have been set but before ordinary actions take place $output
Definition: hooks.txt:2217
testLockForUpdate( $sql, $sqlText)
provideLockForUpdate Wikimedia\Rdbms\Database::lockForUpdate
testSelectFieldValues()
Wikimedia\Rdbms\Database::selectFieldValues()
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return true
Definition: hooks.txt:1982
testTransactionErrorState1()
\Wikimedia\Rdbms\DBTransactionStateError \Wikimedia\Rdbms\Database::assertTransactionStatus ...
testInsertSelect( $sql, $sqlTextNative, $sqlSelect, $sqlInsert)
provideInsertSelect Wikimedia\Rdbms\Database::insertSelect Wikimedia\Rdbms\Database::nativeInsertSele...
DatabaseTestHelper Database $database
testAtomicSectionsTrxRound()
\Wikimedia\Rdbms\Database::doSavepoint \Wikimedia\Rdbms\Database::doReleaseSavepoint \Wikimedia\Rdbms...
static provideLockForUpdate()
testAtomicSectionsRecovery()
\Wikimedia\Rdbms\Database::doSavepoint \Wikimedia\Rdbms\Database::doReleaseSavepoint \Wikimedia\Rdbms...
static provideDeleteJoin()
const LIST_AND
Definition: Defines.php:43
testUpsert( $sql, $sqlText)
provideUpsert Wikimedia\Rdbms\Database::upsert
testUncancellableAtomicSection()
\Wikimedia\Rdbms\Database::cancelAtomic
const LIST_COMMA
Definition: Defines.php:42
testBuildConcat( $stringList, $sqlText)
provideBuildConcat Wikimedia\Rdbms\Database::buildConcat
testDeleteJoin( $sql, $sqlText)
provideDeleteJoin Wikimedia\Rdbms\Database::deleteJoin
Helper for testing the methods from the Database class.
testDropNonExistingTable()
Wikimedia\Rdbms\Database::dropTable.
$params
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:780
testImplicitTransactionRollback()
\Wikimedia\Rdbms\Database::query
testTransactionErrorState2()
\Wikimedia\Rdbms\Database::query
static provideSelect()
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings, LocalSettings).
Definition: Setup.php:123
const LIST_SET
Definition: Defines.php:44
const LIST_OR
Definition: Defines.php:46
const DBO_TRX
Definition: defines.php:12
testUnionConditionPermutations( $params, $expect)
provideUnionConditionPermutations Wikimedia\Rdbms\Database::unionConditionPermutations ...
static provideConditional()
static provideNativeReplace()
testPrematureClose3()
\Wikimedia\Rdbms\Database::close
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
testAtomicSectionsCallbackCancellation()
\Wikimedia\Rdbms\Database::doSavepoint \Wikimedia\Rdbms\Database::doReleaseSavepoint \Wikimedia\Rdbms...
testBuildLike( $array, $sqlText)
provideBuildLike Wikimedia\Rdbms\Database::buildLike Wikimedia\Rdbms\Database::escapeLikeInternal ...
testInsertSelectBatching()
Wikimedia\Rdbms\Database::insertSelect Wikimedia\Rdbms\Database::nativeInsertSelect.
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:38
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
testConditional( $sql, $sqlText)
provideConditional Wikimedia\Rdbms\Database::conditional
testNoAtomicSection( $method)
provideAtomicSectionMethodsForErrors \Wikimedia\Rdbms\Database::endAtomic \Wikimedia\Rdbms\Database::...
testUnionQueries( $sql, $sqlText)
provideUnionQueries Wikimedia\Rdbms\Database::unionQueries
Used by Database::buildLike() to represent characters that have special meaning in SQL LIKE clauses a...
Definition: LikeMatch.php:10
testBuildSubstring_invalidParams( $start, $length)
Wikimedia\Rdbms\Database::buildSubstring Wikimedia\Rdbms\Database::assertBuildSubstringParams provide...
testInsert( $sql, $sqlText)
provideInsert Wikimedia\Rdbms\Database::insert Wikimedia\Rdbms\Database::makeInsertOptions ...
static provideBuildLike()
assertLastSqlDb( $sqlText, DatabaseTestHelper $db)
testPrematureClose2()
\Wikimedia\Rdbms\Database::close
static provideAtomicSectionMethodsForErrors()
testInvalidAtomicSectionEnded( $method)
provideAtomicSectionMethodsForErrors \Wikimedia\Rdbms\Database::endAtomic \Wikimedia\Rdbms\Database::...
testBuildSubstring( $input, $start, $length, $expected)
Wikimedia\Rdbms\Database::buildSubstring provideBuildSubstring.
testDropTable()
Wikimedia\Rdbms\Database::dropTable.
getLastSqls()
Returns SQL queries grouped by &#39;; &#39; Clear the list of queries that have been done so far...
testDelete( $sql, $sqlText)
provideDelete Wikimedia\Rdbms\Database::delete
Test the parts of the Database abstract class that deal with creating SQL text.
testSelectRowCount( $sql, $sqlText)
Wikimedia\Rdbms\Subquery provideSelectRowCount.
testReplace( $sql, $sqlText)
provideReplace Wikimedia\Rdbms\Database::replace
assertLastSql( $sqlText)