Merge pull request #14077 from pradpnayak/AutoComplete
[civicrm-core.git] / tests / phpunit / CRM / Core / TransactionTest.php
1 <?php
2
3 /**
4 * Class CRM_Core_TransactionTest
5 * @group headless
6 */
7 class CRM_Core_TransactionTest extends CiviUnitTestCase {
8
9 /**
10 * @var array
11 */
12 private $callbackLog;
13
14 /**
15 * @var array (int $idx => int $contactId) list of contact IDs that have been created (in order of creation)
16 *
17 * Note that ID this is all IDs created by the test-case -- even if the creation was subsequently rolled back
18 */
19 private $cids;
20
21 public function setUp() {
22 parent::setUp();
23 $this->quickCleanup(array('civicrm_contact', 'civicrm_activity'));
24 $this->callbackLog = array();
25 $this->cids = array();
26 }
27
28 /**
29 * @return array
30 */
31 public function dataCreateStyle() {
32 return array(
33 array('sql-insert'),
34 array('bao-create'),
35 );
36 }
37
38 /**
39 * @return array
40 */
41 public function dataCreateAndCommitStyles() {
42 return array(
43 array('sql-insert', 'implicit-commit'),
44 array('sql-insert', 'explicit-commit'),
45 array('bao-create', 'implicit-commit'),
46 array('bao-create', 'explicit-commit'),
47 );
48 }
49
50 /**
51 * @param string $createStyle
52 * 'sql-insert'|'bao-create'.
53 * @param string $commitStyle
54 * 'implicit-commit'|'explicit-commit'.
55 * @dataProvider dataCreateAndCommitStyles
56 */
57 public function testBasicCommit($createStyle, $commitStyle) {
58 $this->createContactWithTransaction('reuse-tx', $createStyle, $commitStyle);
59 $this->assertCount(1, $this->cids);
60 $this->assertContactsExistByOffset(array(0 => TRUE));
61 }
62
63 /**
64 * @dataProvider dataCreateStyle
65 * @param $createStyle
66 */
67 public function testBasicRollback($createStyle) {
68 $this->createContactWithTransaction('reuse-tx', $createStyle, 'rollback');
69 $this->assertCount(1, $this->cids);
70 $this->assertContactsExistByOffset(array(0 => FALSE));
71 }
72
73 /**
74 * Test in which an outer function makes multiple calls to inner functions.
75 * but then rolls back the entire set.
76 *
77 * @param string $createStyle
78 * 'sql-insert'|'bao-create'.
79 * @param string $commitStyle
80 * 'implicit-commit'|'explicit-commit'.
81 * @dataProvider dataCreateAndCommitStyles
82 */
83 public function testBatchRollback($createStyle, $commitStyle) {
84 $this->runBatch(
85 'reuse-tx',
86 array(
87 // cid 0
88 array('reuse-tx', $createStyle, $commitStyle),
89 // cid 1
90 array('reuse-tx', $createStyle, $commitStyle),
91 ),
92 array(0 => TRUE, 1 => TRUE),
93 'rollback'
94 );
95 $this->assertCount(2, $this->cids);
96 $this->assertContactsExistByOffset(array(0 => FALSE, 1 => FALSE));
97 }
98
99 /**
100 * Test in which runBatch makes multiple calls to
101 * createContactWithTransaction using a mix of rollback/commit.
102 * createContactWithTransaction use nesting (savepoints), so the
103 * batch is able to commit.
104 *
105 * @param string $createStyle
106 * 'sql-insert'|'bao-create'.
107 * @param string $commitStyle
108 * 'implicit-commit'|'explicit-commit'.
109 * @dataProvider dataCreateAndCommitStyles
110 */
111 public function testMixedBatchCommit_nesting($createStyle, $commitStyle) {
112 $this->runBatch(
113 'reuse-tx',
114 array(
115 // cid 0
116 array('nest-tx', $createStyle, $commitStyle),
117 // cid 1
118 array('nest-tx', $createStyle, 'rollback'),
119 // cid 2
120 array('nest-tx', $createStyle, $commitStyle),
121 ),
122 array(0 => TRUE, 1 => FALSE, 2 => TRUE),
123 $commitStyle
124 );
125 $this->assertCount(3, $this->cids);
126 $this->assertContactsExistByOffset(array(0 => TRUE, 1 => FALSE, 2 => TRUE));
127 }
128
129 /**
130 * Test in which runBatch makes multiple calls to
131 * createContactWithTransaction using a mix of rollback/commit.
132 * createContactWithTransaction reuses the main transaction,
133 * so the overall batch must rollback.
134 *
135 * @param string $createStyle
136 * 'sql-insert'|'bao-create'.
137 * @param string $commitStyle
138 * 'implicit-commit'|'explicit-commit'.
139 * @dataProvider dataCreateAndCommitStyles
140 */
141 public function testMixedBatchCommit_reuse($createStyle, $commitStyle) {
142 $this->runBatch(
143 'reuse-tx',
144 array(
145 // cid 0
146 array('reuse-tx', $createStyle, $commitStyle),
147 // cid 1
148 array('reuse-tx', $createStyle, 'rollback'),
149 // cid 2
150 array('reuse-tx', $createStyle, $commitStyle),
151 ),
152 array(0 => TRUE, 1 => TRUE, 2 => TRUE),
153 $commitStyle
154 );
155 $this->assertCount(3, $this->cids);
156 $this->assertContactsExistByOffset(array(0 => FALSE, 1 => FALSE, 2 => FALSE));
157 }
158
159 /**
160 * Test in which runBatch makes multiple calls to
161 * createContactWithTransaction using a mix of rollback/commit.
162 * The overall batch is rolled back.
163 *
164 * @param string $createStyle
165 * 'sql-insert'|'bao-create'.
166 * @param string $commitStyle
167 * 'implicit-commit'|'explicit-commit'.
168 * @dataProvider dataCreateAndCommitStyles
169 */
170 public function testMixedBatchRollback_nesting($createStyle, $commitStyle) {
171 $this->assertFalse(CRM_Core_Transaction::isActive());
172 $this->runBatch(
173 'reuse-tx',
174 array(
175 // cid 0
176 array('nest-tx', $createStyle, $commitStyle),
177 // cid 1
178 array('nest-tx', $createStyle, 'rollback'),
179 // cid 2
180 array('nest-tx', $createStyle, $commitStyle),
181 ),
182 array(0 => TRUE, 1 => FALSE, 2 => TRUE),
183 'rollback'
184 );
185 $this->assertFalse(CRM_Core_Transaction::isActive());
186 $this->assertCount(3, $this->cids);
187 $this->assertContactsExistByOffset(array(0 => FALSE, 1 => FALSE, 2 => FALSE));
188 }
189
190 public function testIsActive() {
191 $this->assertEquals(FALSE, CRM_Core_Transaction::isActive());
192 $this->assertEquals(TRUE, CRM_Core_Transaction::willCommit());
193 $tx = new CRM_Core_Transaction();
194 $this->assertEquals(TRUE, CRM_Core_Transaction::isActive());
195 $this->assertEquals(TRUE, CRM_Core_Transaction::willCommit());
196 $tx = NULL;
197 $this->assertEquals(FALSE, CRM_Core_Transaction::isActive());
198 $this->assertEquals(TRUE, CRM_Core_Transaction::willCommit());
199 }
200
201 public function testIsActive_rollback() {
202 $this->assertEquals(FALSE, CRM_Core_Transaction::isActive());
203 $this->assertEquals(TRUE, CRM_Core_Transaction::willCommit());
204
205 $tx = new CRM_Core_Transaction();
206 $this->assertEquals(TRUE, CRM_Core_Transaction::isActive());
207 $this->assertEquals(TRUE, CRM_Core_Transaction::willCommit());
208
209 $tx->rollback();
210 $this->assertEquals(TRUE, CRM_Core_Transaction::isActive());
211 $this->assertEquals(FALSE, CRM_Core_Transaction::willCommit());
212
213 $tx = NULL;
214 $this->assertEquals(FALSE, CRM_Core_Transaction::isActive());
215 $this->assertEquals(TRUE, CRM_Core_Transaction::willCommit());
216 }
217
218 public function testCallback_commit() {
219 $tx = new CRM_Core_Transaction();
220
221 CRM_Core_Transaction::addCallback(CRM_Core_Transaction::PHASE_PRE_COMMIT, array($this, '_preCommit'), array(
222 'qwe',
223 'rty',
224 ));
225 CRM_Core_Transaction::addCallback(CRM_Core_Transaction::PHASE_POST_COMMIT, array($this, '_postCommit'), array(
226 'uio',
227 'p[]',
228 ));
229 CRM_Core_Transaction::addCallback(CRM_Core_Transaction::PHASE_PRE_ROLLBACK, array(
230 $this,
231 '_preRollback',
232 ), array('asd', 'fgh'));
233 CRM_Core_Transaction::addCallback(CRM_Core_Transaction::PHASE_POST_ROLLBACK, array(
234 $this,
235 '_postRollback',
236 ), array('jkl', ';'));
237
238 CRM_Core_DAO::executeQuery('UPDATE civicrm_contact SET id = 100 WHERE id = 100');
239
240 $this->assertEquals(array(), $this->callbackLog);
241 $tx = NULL;
242 $this->assertEquals(array('_preCommit', 'qwe', 'rty'), $this->callbackLog[0]);
243 $this->assertEquals(array('_postCommit', 'uio', 'p[]'), $this->callbackLog[1]);
244 }
245
246 public function testCallback_rollback() {
247 $tx = new CRM_Core_Transaction();
248
249 CRM_Core_Transaction::addCallback(CRM_Core_Transaction::PHASE_PRE_COMMIT, array($this, '_preCommit'), array(
250 'ewq',
251 'ytr',
252 ));
253 CRM_Core_Transaction::addCallback(CRM_Core_Transaction::PHASE_POST_COMMIT, array($this, '_postCommit'), array(
254 'oiu',
255 '][p',
256 ));
257 CRM_Core_Transaction::addCallback(CRM_Core_Transaction::PHASE_PRE_ROLLBACK, array(
258 $this,
259 '_preRollback',
260 ), array('dsa', 'hgf'));
261 CRM_Core_Transaction::addCallback(CRM_Core_Transaction::PHASE_POST_ROLLBACK, array(
262 $this,
263 '_postRollback',
264 ), array('lkj', ';'));
265
266 CRM_Core_DAO::executeQuery('UPDATE civicrm_contact SET id = 100 WHERE id = 100');
267 $tx->rollback();
268
269 $this->assertEquals(array(), $this->callbackLog);
270 $tx = NULL;
271 $this->assertEquals(array('_preRollback', 'dsa', 'hgf'), $this->callbackLog[0]);
272 $this->assertEquals(array('_postRollback', 'lkj', ';'), $this->callbackLog[1]);
273 }
274
275 /**
276 * @param string $createStyle
277 * 'sql-insert'|'bao-create'.
278 * @param string $commitStyle
279 * 'implicit-commit'|'explicit-commit'.
280 * @dataProvider dataCreateAndCommitStyles
281 */
282 public function testRun_ok($createStyle, $commitStyle) {
283 $test = $this;
284 CRM_Core_Transaction::create(TRUE)->run(function ($tx) use (&$test, $createStyle, $commitStyle) {
285 $test->createContactWithTransaction('nest-tx', $createStyle, $commitStyle);
286 $test->assertContactsExistByOffset(array(0 => TRUE));
287 });
288 $this->assertContactsExistByOffset(array(0 => TRUE));
289 }
290
291 /**
292 * @param string $createStyle
293 * 'sql-insert'|'bao-create'.
294 * @param string $commitStyle
295 * 'implicit-commit'|'explicit-commit'.
296 * @dataProvider dataCreateAndCommitStyles
297 */
298 public function testRun_exception($createStyle, $commitStyle) {
299 $tx = new CRM_Core_Transaction();
300 $test = $this;
301 // Exception
302 $e = NULL;
303 try {
304 CRM_Core_Transaction::create(TRUE)->run(function ($tx) use (&$test, $createStyle, $commitStyle) {
305 $test->createContactWithTransaction('nest-tx', $createStyle, $commitStyle);
306 $test->assertContactsExistByOffset(array(0 => TRUE));
307 throw new Exception("Ruh-roh");
308 });
309 }
310 catch (Exception $ex) {
311 $e = $ex;
312 if (get_class($e) != 'Exception' || $e->getMessage() != 'Ruh-roh') {
313 throw $e;
314 }
315 }
316 $this->assertTrue($e instanceof Exception);
317 $this->assertContactsExistByOffset(array(0 => FALSE));
318 }
319
320 /**
321 * @param $cids
322 * @param bool $exist
323 */
324 public function assertContactsExist($cids, $exist = TRUE) {
325 foreach ($cids as $cid) {
326 $this->assertTrue(is_numeric($cid));
327 $this->assertDBQuery($exist ? 1 : 0, 'SELECT count(*) FROM civicrm_contact WHERE id = %1', array(
328 1 => array($cid, 'Integer'),
329 ));
330 }
331 }
332
333 /**
334 * @param array $existsByOffset
335 * Array(int $cidOffset => bool $expectExists).
336 * @param int $generalOffset
337 */
338 public function assertContactsExistByOffset($existsByOffset, $generalOffset = 0) {
339 foreach ($existsByOffset as $offset => $expectExists) {
340 $this->assertTrue(isset($this->cids[$generalOffset + $offset]), "Find cid at offset($generalOffset + $offset)");
341 $cid = $this->cids[$generalOffset + $offset];
342 $this->assertTrue(is_numeric($cid));
343 $this->assertDBQuery($expectExists ? 1 : 0, 'SELECT count(*) FROM civicrm_contact WHERE id = %1', array(
344 1 => array($cid, 'Integer'),
345 ), "Check contact at offset($generalOffset + $offset)");
346 }
347 }
348
349 /**
350 * Use SQL to INSERT a contact and assert success. Perform
351 * work within a transaction.
352 *
353 * @param string $nesting
354 * 'reuse-tx'|'nest-tx' how to construct transaction.
355 * @param string $insert
356 * 'sql-insert'|'bao-create' how to add the example record.
357 * @param string $outcome
358 * 'rollback'|'implicit-commit'|'explicit-commit' how to finish transaction.
359 * @return int
360 * cid
361 */
362 public function createContactWithTransaction($nesting, $insert, $outcome) {
363 if ($nesting != 'reuse-tx' && $nesting != 'nest-tx') {
364 throw new RuntimeException('Bad test data: reuse=' . $nesting);
365 }
366 if ($insert != 'sql-insert' && $insert != 'bao-create') {
367 throw new RuntimeException('Bad test data: insert=' . $insert);
368 }
369 if ($outcome != 'rollback' && $outcome != 'implicit-commit' && $outcome != 'explicit-commit') {
370 throw new RuntimeException('Bad test data: outcome=' . $outcome);
371 }
372
373 $tx = new CRM_Core_Transaction($nesting === 'nest-tx');
374
375 if ($insert == 'sql-insert') {
376 $r = CRM_Core_DAO::executeQuery("INSERT INTO civicrm_contact(first_name,last_name) VALUES ('ff', 'll')");
377 $cid = $r->getConnection()->lastInsertId();
378 }
379 elseif ($insert == 'bao-create') {
380 $params = array(
381 'contact_type' => 'Individual',
382 'first_name' => 'FF',
383 'last_name' => 'LL',
384 );
385 $r = CRM_Contact_BAO_Contact::create($params);
386 $cid = $r->id;
387 }
388
389 $this->cids[] = $cid;
390
391 $this->assertContactsExist(array($cid), TRUE);
392
393 if ($outcome == 'rollback') {
394 $tx->rollback();
395 }
396 elseif ($outcome == 'explicit-commit') {
397 $tx->commit();
398 } // else: implicit-commit
399
400 return $cid;
401 }
402
403 /**
404 * Perform a series of operations within smaller transactions.
405 *
406 * @param string $nesting
407 * 'reuse-tx'|'nest-tx' how to construct transaction.
408 * @param array $callbacks
409 * See createContactWithTransaction.
410 * @param array $existsByOffset
411 * See assertContactsMix.
412 * @param string $outcome
413 * 'rollback'|'implicit-commit'|'explicit-commit' how to finish transaction.
414 * @return void
415 */
416 public function runBatch($nesting, $callbacks, $existsByOffset, $outcome) {
417 if ($nesting != 'reuse-tx' && $nesting != 'nest-tx') {
418 throw new RuntimeException('Bad test data: nesting=' . $nesting);
419 }
420 if ($outcome != 'rollback' && $outcome != 'implicit-commit' && $outcome != 'explicit-commit') {
421 throw new RuntimeException('Bad test data: outcome=' . $nesting);
422 }
423
424 $tx = new CRM_Core_Transaction($nesting === 'reuse-tx');
425
426 $generalOffset = count($this->cids);
427 foreach ($callbacks as $callback) {
428 list ($cbNesting, $cbInsert, $cbOutcome) = $callback;
429 $this->createContactWithTransaction($cbNesting, $cbInsert, $cbOutcome);
430 }
431
432 $this->assertContactsExistByOffset($existsByOffset, $generalOffset);
433
434 if ($outcome == 'rollback') {
435 $tx->rollback();
436 }
437 elseif ($outcome == 'explicit-commit') {
438 $tx->commit();
439 } // else: implicit-commit
440 }
441
442 /**
443 * @param $arg1
444 * @param $arg2
445 */
446 public function _preCommit($arg1, $arg2) {
447 $this->callbackLog[] = array('_preCommit', $arg1, $arg2);
448 }
449
450 /**
451 * @param $arg1
452 * @param $arg2
453 */
454 public function _postCommit($arg1, $arg2) {
455 $this->callbackLog[] = array('_postCommit', $arg1, $arg2);
456 }
457
458 /**
459 * @param $arg1
460 * @param $arg2
461 */
462 public function _preRollback($arg1, $arg2) {
463 $this->callbackLog[] = array('_preRollback', $arg1, $arg2);
464 }
465
466 /**
467 * @param $arg1
468 * @param $arg2
469 */
470 public function _postRollback($arg1, $arg2) {
471 $this->callbackLog[] = array('_postRollback', $arg1, $arg2);
472 }
473
474 }