Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
15403 manish.sha 1
<?php
2
/**
3
 * DboSourceTest file
4
 *
5
 * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
6
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
7
 *
8
 * Licensed under The MIT License
9
 * For full copyright and license information, please see the LICENSE.txt
10
 * Redistributions of files must retain the above copyright notice.
11
 *
12
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
13
 * @link          http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
14
 * @package       Cake.Test.Case.Model.Datasource
15
 * @since         CakePHP(tm) v 1.2.0.4206
16
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
17
 */
18
 
19
App::uses('Model', 'Model');
20
App::uses('AppModel', 'Model');
21
App::uses('DataSource', 'Model/Datasource');
22
App::uses('DboSource', 'Model/Datasource');
23
App::uses('DboTestSource', 'Model/Datasource');
24
App::uses('DboSecondTestSource', 'Model/Datasource');
25
App::uses('MockDataSource', 'Model/Datasource');
26
 
27
require_once dirname(dirname(__FILE__)) . DS . 'models.php';
28
 
29
/**
30
 * Class MockPDO
31
 *
32
 * @package       Cake.Test.Case.Model.Datasource
33
 */
34
class MockPDO extends PDO {
35
 
36
/**
37
 * Constructor.
38
 */
39
	public function __construct() {
40
	}
41
 
42
}
43
 
44
/**
45
 * Class MockDataSource
46
 *
47
 * @package       Cake.Test.Case.Model.Datasource
48
 */
49
class MockDataSource extends DataSource {
50
}
51
 
52
/**
53
 * Class DboTestSource
54
 *
55
 * @package       Cake.Test.Case.Model.Datasource
56
 */
57
class DboTestSource extends DboSource {
58
 
59
	public $nestedSupport = false;
60
 
61
	public function connect($config = array()) {
62
		$this->connected = true;
63
	}
64
 
65
	public function mergeAssociation(&$data, &$merge, $association, $type, $selfJoin = false) {
66
		return parent::_mergeAssociation($data, $merge, $association, $type, $selfJoin);
67
	}
68
 
69
	public function setConfig($config = array()) {
70
		$this->config = $config;
71
	}
72
 
73
	public function setConnection($conn) {
74
		$this->_connection = $conn;
75
	}
76
 
77
	public function nestedTransactionSupported() {
78
		return $this->useNestedTransactions && $this->nestedSupport;
79
	}
80
 
81
}
82
 
83
/**
84
 * Class DboSecondTestSource
85
 *
86
 * @package       Cake.Test.Case.Model.Datasource
87
 */
88
class DboSecondTestSource extends DboSource {
89
 
90
	public $startQuote = '_';
91
 
92
	public $endQuote = '_';
93
 
94
	public function connect($config = array()) {
95
		$this->connected = true;
96
	}
97
 
98
	public function mergeAssociation(&$data, &$merge, $association, $type, $selfJoin = false) {
99
		return parent::_mergeAssociation($data, $merge, $association, $type, $selfJoin);
100
	}
101
 
102
	public function setConfig($config = array()) {
103
		$this->config = $config;
104
	}
105
 
106
	public function setConnection($conn) {
107
		$this->_connection = $conn;
108
	}
109
 
110
}
111
 
112
/**
113
 * DboSourceTest class
114
 *
115
 * @package       Cake.Test.Case.Model.Datasource
116
 */
117
class DboSourceTest extends CakeTestCase {
118
 
119
/**
120
 * autoFixtures property
121
 *
122
 * @var bool
123
 */
124
	public $autoFixtures = false;
125
 
126
/**
127
 * fixtures property
128
 *
129
 * @var array
130
 */
131
	public $fixtures = array(
132
		'core.apple', 'core.article', 'core.articles_tag', 'core.attachment', 'core.comment',
133
		'core.sample', 'core.tag', 'core.user', 'core.post', 'core.author', 'core.data_test'
134
	);
135
 
136
/**
137
 * setUp method
138
 *
139
 * @return void
140
 */
141
	public function setUp() {
142
		parent::setUp();
143
 
144
		$this->testDb = new DboTestSource();
145
		$this->testDb->cacheSources = false;
146
		$this->testDb->startQuote = '`';
147
		$this->testDb->endQuote = '`';
148
 
149
		$this->Model = new TestModel();
150
	}
151
 
152
/**
153
 * tearDown method
154
 *
155
 * @return void
156
 */
157
	public function tearDown() {
158
		parent::tearDown();
159
		unset($this->Model);
160
	}
161
 
162
/**
163
 * test that booleans and null make logical condition strings.
164
 *
165
 * @return void
166
 */
167
	public function testBooleanNullConditionsParsing() {
168
		$result = $this->testDb->conditions(true);
169
		$this->assertEquals(' WHERE 1 = 1', $result, 'true conditions failed %s');
170
 
171
		$result = $this->testDb->conditions(false);
172
		$this->assertEquals(' WHERE 0 = 1', $result, 'false conditions failed %s');
173
 
174
		$result = $this->testDb->conditions(null);
175
		$this->assertEquals(' WHERE 1 = 1', $result, 'null conditions failed %s');
176
 
177
		$result = $this->testDb->conditions(array());
178
		$this->assertEquals(' WHERE 1 = 1', $result, 'array() conditions failed %s');
179
 
180
		$result = $this->testDb->conditions('');
181
		$this->assertEquals(' WHERE 1 = 1', $result, '"" conditions failed %s');
182
 
183
		$result = $this->testDb->conditions(' ', '"  " conditions failed %s');
184
		$this->assertEquals(' WHERE 1 = 1', $result);
185
	}
186
 
187
/**
188
 * test that booleans work on empty set.
189
 *
190
 * @return void
191
 */
192
	public function testBooleanEmptyConditionsParsing() {
193
		$result = $this->testDb->conditions(array('OR' => array()));
194
		$this->assertEquals(' WHERE  1 = 1', $result, 'empty conditions failed');
195
 
196
		$result = $this->testDb->conditions(array('OR' => array('OR' => array())));
197
		$this->assertEquals(' WHERE  1 = 1', $result, 'nested empty conditions failed');
198
	}
199
 
200
/**
201
 * test that order() will accept objects made from DboSource::expression
202
 *
203
 * @return void
204
 */
205
	public function testOrderWithExpression() {
206
		$expression = $this->testDb->expression("CASE Sample.id WHEN 1 THEN 'Id One' ELSE 'Other Id' END AS case_col");
207
		$result = $this->testDb->order($expression);
208
		$expected = " ORDER BY CASE Sample.id WHEN 1 THEN 'Id One' ELSE 'Other Id' END AS case_col";
209
		$this->assertEquals($expected, $result);
210
	}
211
 
212
/**
213
 * testMergeAssociations method
214
 *
215
 * @return void
216
 */
217
	public function testMergeAssociations() {
218
		$data = array('Article2' => array(
219
				'id' => '1', 'user_id' => '1', 'title' => 'First Article',
220
				'body' => 'First Article Body', 'published' => 'Y',
221
				'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31'
222
		));
223
		$merge = array('Topic' => array(array(
224
			'id' => '1', 'topic' => 'Topic', 'created' => '2007-03-17 01:16:23',
225
			'updated' => '2007-03-17 01:18:31'
226
		)));
227
		$expected = array(
228
			'Article2' => array(
229
				'id' => '1', 'user_id' => '1', 'title' => 'First Article',
230
				'body' => 'First Article Body', 'published' => 'Y',
231
				'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31'
232
			),
233
			'Topic' => array(
234
				'id' => '1', 'topic' => 'Topic', 'created' => '2007-03-17 01:16:23',
235
				'updated' => '2007-03-17 01:18:31'
236
			)
237
		);
238
		$this->testDb->mergeAssociation($data, $merge, 'Topic', 'hasOne');
239
		$this->assertEquals($expected, $data);
240
 
241
		$data = array('Article2' => array(
242
				'id' => '1', 'user_id' => '1', 'title' => 'First Article',
243
				'body' => 'First Article Body', 'published' => 'Y',
244
				'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31'
245
		));
246
		$merge = array('User2' => array(array(
247
			'id' => '1', 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99',
248
			'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
249
		)));
250
 
251
		$expected = array(
252
			'Article2' => array(
253
				'id' => '1', 'user_id' => '1', 'title' => 'First Article',
254
				'body' => 'First Article Body', 'published' => 'Y',
255
				'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31'
256
			),
257
			'User2' => array(
258
				'id' => '1', 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
259
			)
260
		);
261
		$this->testDb->mergeAssociation($data, $merge, 'User2', 'belongsTo');
262
		$this->assertEquals($expected, $data);
263
 
264
		$data = array(
265
			'Article2' => array(
266
				'id' => '1', 'user_id' => '1', 'title' => 'First Article', 'body' => 'First Article Body', 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31'
267
			)
268
		);
269
		$merge = array(array('Comment' => false));
270
		$expected = array(
271
			'Article2' => array(
272
				'id' => '1', 'user_id' => '1', 'title' => 'First Article', 'body' => 'First Article Body', 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31'
273
			),
274
			'Comment' => array()
275
		);
276
		$this->testDb->mergeAssociation($data, $merge, 'Comment', 'hasMany');
277
		$this->assertEquals($expected, $data);
278
 
279
		$data = array(
280
			'Article' => array(
281
				'id' => '1', 'user_id' => '1', 'title' => 'First Article', 'body' => 'First Article Body', 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31'
282
			)
283
		);
284
		$merge = array(
285
			array(
286
				'Comment' => array(
287
					'id' => '1', 'comment' => 'Comment 1', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
288
				)
289
			),
290
			array(
291
				'Comment' => array(
292
					'id' => '2', 'comment' => 'Comment 2', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
293
				)
294
			)
295
		);
296
		$expected = array(
297
			'Article' => array(
298
				'id' => '1', 'user_id' => '1', 'title' => 'First Article', 'body' => 'First Article Body', 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31'
299
			),
300
			'Comment' => array(
301
				array(
302
					'id' => '1', 'comment' => 'Comment 1', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
303
				),
304
				array(
305
					'id' => '2', 'comment' => 'Comment 2', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
306
				)
307
			)
308
		);
309
		$this->testDb->mergeAssociation($data, $merge, 'Comment', 'hasMany');
310
		$this->assertEquals($expected, $data);
311
 
312
		$data = array(
313
			'Article' => array(
314
				'id' => '1', 'user_id' => '1', 'title' => 'First Article', 'body' => 'First Article Body', 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31'
315
			)
316
		);
317
		$merge = array(
318
			array(
319
				'Comment' => array(
320
					'id' => '1', 'comment' => 'Comment 1', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
321
				),
322
				'User2' => array(
323
					'id' => '1', 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
324
				)
325
			),
326
			array(
327
				'Comment' => array(
328
					'id' => '2', 'comment' => 'Comment 2', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
329
				),
330
				'User2' => array(
331
					'id' => '1', 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
332
				)
333
			)
334
		);
335
		$expected = array(
336
			'Article' => array(
337
				'id' => '1', 'user_id' => '1', 'title' => 'First Article', 'body' => 'First Article Body', 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31'
338
			),
339
			'Comment' => array(
340
				array(
341
					'id' => '1', 'comment' => 'Comment 1', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31',
342
					'User2' => array(
343
						'id' => '1', 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
344
					)
345
				),
346
				array(
347
					'id' => '2', 'comment' => 'Comment 2', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31',
348
					'User2' => array(
349
						'id' => '1', 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
350
					)
351
				)
352
			)
353
		);
354
		$this->testDb->mergeAssociation($data, $merge, 'Comment', 'hasMany');
355
		$this->assertEquals($expected, $data);
356
 
357
		$data = array(
358
			'Article' => array(
359
				'id' => '1', 'user_id' => '1', 'title' => 'First Article', 'body' => 'First Article Body', 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31'
360
			)
361
		);
362
		$merge = array(
363
			array(
364
				'Comment' => array(
365
					'id' => '1', 'comment' => 'Comment 1', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
366
				),
367
				'User2' => array(
368
					'id' => '1', 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
369
				),
370
				'Tag' => array(
371
					array('id' => 1, 'tag' => 'Tag 1'),
372
					array('id' => 2, 'tag' => 'Tag 2')
373
				)
374
			),
375
			array(
376
				'Comment' => array(
377
					'id' => '2', 'comment' => 'Comment 2', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
378
				),
379
				'User2' => array(
380
					'id' => '1', 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
381
				),
382
				'Tag' => array()
383
			)
384
		);
385
		$expected = array(
386
			'Article' => array(
387
				'id' => '1', 'user_id' => '1', 'title' => 'First Article', 'body' => 'First Article Body', 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31'
388
			),
389
			'Comment' => array(
390
				array(
391
					'id' => '1', 'comment' => 'Comment 1', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31',
392
					'User2' => array(
393
						'id' => '1', 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
394
					),
395
					'Tag' => array(
396
						array('id' => 1, 'tag' => 'Tag 1'),
397
						array('id' => 2, 'tag' => 'Tag 2')
398
					)
399
				),
400
				array(
401
					'id' => '2', 'comment' => 'Comment 2', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31',
402
					'User2' => array(
403
						'id' => '1', 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
404
					),
405
					'Tag' => array()
406
				)
407
			)
408
		);
409
		$this->testDb->mergeAssociation($data, $merge, 'Comment', 'hasMany');
410
		$this->assertEquals($expected, $data);
411
 
412
		$data = array(
413
			'Article' => array(
414
				'id' => '1', 'user_id' => '1', 'title' => 'First Article', 'body' => 'First Article Body', 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31'
415
			)
416
		);
417
		$merge = array(
418
			array(
419
				'Tag' => array(
420
					'id' => '1', 'tag' => 'Tag 1', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
421
				)
422
			),
423
			array(
424
				'Tag' => array(
425
					'id' => '2', 'tag' => 'Tag 2', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
426
				)
427
			),
428
			array(
429
				'Tag' => array(
430
					'id' => '3', 'tag' => 'Tag 3', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
431
				)
432
			)
433
		);
434
		$expected = array(
435
			'Article' => array(
436
				'id' => '1', 'user_id' => '1', 'title' => 'First Article', 'body' => 'First Article Body', 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31'
437
			),
438
			'Tag' => array(
439
				array(
440
					'id' => '1', 'tag' => 'Tag 1', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
441
				),
442
				array(
443
					'id' => '2', 'tag' => 'Tag 2', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
444
				),
445
				array(
446
					'id' => '3', 'tag' => 'Tag 3', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
447
				)
448
			)
449
		);
450
		$this->testDb->mergeAssociation($data, $merge, 'Tag', 'hasAndBelongsToMany');
451
		$this->assertEquals($expected, $data);
452
 
453
		$data = array(
454
			'Article' => array(
455
				'id' => '1', 'user_id' => '1', 'title' => 'First Article', 'body' => 'First Article Body', 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31'
456
			)
457
		);
458
		$merge = array(
459
			array(
460
				'Tag' => array(
461
					'id' => '1', 'tag' => 'Tag 1', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
462
				)
463
			),
464
			array(
465
				'Tag' => array(
466
					'id' => '2', 'tag' => 'Tag 2', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
467
				)
468
			),
469
			array(
470
				'Tag' => array(
471
					'id' => '3', 'tag' => 'Tag 3', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'
472
				)
473
			)
474
		);
475
		$expected = array(
476
			'Article' => array(
477
				'id' => '1', 'user_id' => '1', 'title' => 'First Article', 'body' => 'First Article Body', 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31'
478
			),
479
			'Tag' => array('id' => '1', 'tag' => 'Tag 1', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31')
480
		);
481
		$this->testDb->mergeAssociation($data, $merge, 'Tag', 'hasOne');
482
		$this->assertEquals($expected, $data);
483
	}
484
 
485
/**
486
 * testMagicMethodQuerying method
487
 *
488
 * @return void
489
 */
490
	public function testMagicMethodQuerying() {
491
		$result = $this->db->query('findByFieldName', array('value'), $this->Model);
492
		$expected = array('first', array(
493
			'conditions' => array('TestModel.field_name' => 'value'),
494
			'fields' => null, 'order' => null, 'recursive' => null
495
		));
496
		$this->assertEquals($expected, $result);
497
 
498
		$result = $this->db->query('findByFindBy', array('value'), $this->Model);
499
		$expected = array('first', array(
500
			'conditions' => array('TestModel.find_by' => 'value'),
501
			'fields' => null, 'order' => null, 'recursive' => null
502
		));
503
		$this->assertEquals($expected, $result);
504
 
505
		$result = $this->db->query('findAllByFieldName', array('value'), $this->Model);
506
		$expected = array('all', array(
507
			'conditions' => array('TestModel.field_name' => 'value'),
508
			'fields' => null, 'order' => null, 'limit' => null,
509
			'page' => null, 'recursive' => null
510
		));
511
		$this->assertEquals($expected, $result);
512
 
513
		$result = $this->db->query('findAllById', array('a'), $this->Model);
514
		$expected = array('all', array(
515
			'conditions' => array('TestModel.id' => 'a'),
516
			'fields' => null, 'order' => null, 'limit' => null,
517
			'page' => null, 'recursive' => null
518
		));
519
		$this->assertEquals($expected, $result);
520
 
521
		$result = $this->db->query('findByFieldName', array(array('value1', 'value2', 'value3')), $this->Model);
522
		$expected = array('first', array(
523
			'conditions' => array('TestModel.field_name' => array('value1', 'value2', 'value3')),
524
			'fields' => null, 'order' => null, 'recursive' => null
525
		));
526
		$this->assertEquals($expected, $result);
527
 
528
		$result = $this->db->query('findByFieldName', array(null), $this->Model);
529
		$expected = array('first', array(
530
			'conditions' => array('TestModel.field_name' => null),
531
			'fields' => null, 'order' => null, 'recursive' => null
532
		));
533
		$this->assertEquals($expected, $result);
534
 
535
		$result = $this->db->query('findByFieldName', array('= a'), $this->Model);
536
		$expected = array('first', array(
537
			'conditions' => array('TestModel.field_name' => '= a'),
538
			'fields' => null, 'order' => null, 'recursive' => null
539
		));
540
		$this->assertEquals($expected, $result);
541
 
542
		$result = $this->db->query('findByFieldName', array(), $this->Model);
543
		$expected = false;
544
		$this->assertEquals($expected, $result);
545
	}
546
 
547
/**
548
 * @expectedException PDOException
549
 * @return void
550
 */
551
	public function testDirectCallThrowsException() {
552
		$this->db->query('directCall', array(), $this->Model);
553
	}
554
 
555
/**
556
 * testValue method
557
 *
558
 * @return void
559
 */
560
	public function testValue() {
561
		if ($this->db instanceof Sqlserver) {
562
			$this->markTestSkipped('Cannot run this test with SqlServer');
563
		}
564
		$result = $this->db->value('{$__cakeForeignKey__$}');
565
		$this->assertEquals('{$__cakeForeignKey__$}', $result);
566
 
567
		$result = $this->db->value(array('first', 2, 'third'));
568
		$expected = array('\'first\'', 2, '\'third\'');
569
		$this->assertEquals($expected, $result);
570
	}
571
 
572
/**
573
 * Tests if the connection can be re-established and that the new (optional) config is set.
574
 *
575
 * @return void
576
 */
577
	public function testReconnect() {
578
		$this->testDb->reconnect(array('prefix' => 'foo'));
579
		$this->assertTrue($this->testDb->connected);
580
		$this->assertEquals('foo', $this->testDb->config['prefix']);
581
	}
582
 
583
/**
584
 * testName method
585
 *
586
 * @return void
587
 */
588
	public function testName() {
589
		$result = $this->testDb->name('name');
590
		$expected = '`name`';
591
		$this->assertEquals($expected, $result);
592
 
593
		$result = $this->testDb->name(array('name', 'Model.*'));
594
		$expected = array('`name`', '`Model`.*');
595
		$this->assertEquals($expected, $result);
596
 
597
		$result = $this->testDb->name('MTD()');
598
		$expected = 'MTD()';
599
		$this->assertEquals($expected, $result);
600
 
601
		$result = $this->testDb->name('(sm)');
602
		$expected = '(sm)';
603
		$this->assertEquals($expected, $result);
604
 
605
		$result = $this->testDb->name('name AS x');
606
		$expected = '`name` AS `x`';
607
		$this->assertEquals($expected, $result);
608
 
609
		$result = $this->testDb->name('Model.name AS x');
610
		$expected = '`Model`.`name` AS `x`';
611
		$this->assertEquals($expected, $result);
612
 
613
		$result = $this->testDb->name('Function(Something.foo)');
614
		$expected = 'Function(`Something`.`foo`)';
615
		$this->assertEquals($expected, $result);
616
 
617
		$result = $this->testDb->name('Function(SubFunction(Something.foo))');
618
		$expected = 'Function(SubFunction(`Something`.`foo`))';
619
		$this->assertEquals($expected, $result);
620
 
621
		$result = $this->testDb->name('Function(Something.foo) AS x');
622
		$expected = 'Function(`Something`.`foo`) AS `x`';
623
		$this->assertEquals($expected, $result);
624
 
625
		$result = $this->testDb->name('I18n__title__pt-br.locale');
626
		$expected = '`I18n__title__pt-br`.`locale`';
627
		$this->assertEquals($expected, $result);
628
 
629
		$result = $this->testDb->name('name-with-minus');
630
		$expected = '`name-with-minus`';
631
		$this->assertEquals($expected, $result);
632
 
633
		$result = $this->testDb->name(array('my-name', 'Foo-Model.*'));
634
		$expected = array('`my-name`', '`Foo-Model`.*');
635
		$this->assertEquals($expected, $result);
636
 
637
		$result = $this->testDb->name(array('Team.P%', 'Team.G/G'));
638
		$expected = array('`Team`.`P%`', '`Team`.`G/G`');
639
		$this->assertEquals($expected, $result);
640
 
641
		$result = $this->testDb->name('Model.name as y');
642
		$expected = '`Model`.`name` AS `y`';
643
		$this->assertEquals($expected, $result);
644
	}
645
 
646
/**
647
 * test that cacheMethod works as expected
648
 *
649
 * @return void
650
 */
651
	public function testCacheMethod() {
652
		$this->testDb->cacheMethods = true;
653
		$result = $this->testDb->cacheMethod('name', 'some-key', 'stuff');
654
		$this->assertEquals('stuff', $result);
655
 
656
		$result = $this->testDb->cacheMethod('name', 'some-key');
657
		$this->assertEquals('stuff', $result);
658
 
659
		$result = $this->testDb->cacheMethod('conditions', 'some-key');
660
		$this->assertNull($result);
661
 
662
		$result = $this->testDb->cacheMethod('name', 'other-key');
663
		$this->assertNull($result);
664
 
665
		$this->testDb->cacheMethods = false;
666
		$result = $this->testDb->cacheMethod('name', 'some-key', 'stuff');
667
		$this->assertEquals('stuff', $result);
668
 
669
		$result = $this->testDb->cacheMethod('name', 'some-key');
670
		$this->assertNull($result);
671
	}
672
 
673
/**
674
 * Test that rare collisions do not happen with method caching
675
 *
676
 * @return void
677
 */
678
	public function testNameMethodCacheCollisions() {
679
		$this->testDb->cacheMethods = true;
680
		$this->testDb->flushMethodCache();
681
		$this->testDb->name('Model.fieldlbqndkezcoapfgirmjsh');
682
		$result = $this->testDb->name('Model.fieldkhdfjmelarbqnzsogcpi');
683
		$expected = '`Model`.`fieldkhdfjmelarbqnzsogcpi`';
684
		$this->assertEquals($expected, $result);
685
	}
686
 
687
/**
688
 * Test that flushMethodCache works as expected
689
 *
690
 * @return void
691
 */
692
	public function testFlushMethodCache() {
693
		$this->testDb->cacheMethods = true;
694
		$this->testDb->cacheMethod('name', 'some-key', 'stuff');
695
 
696
		Cache::write('method_cache', DboTestSource::$methodCache, '_cake_core_');
697
 
698
		$this->testDb->flushMethodCache();
699
		$result = $this->testDb->cacheMethod('name', 'some-key');
700
		$this->assertNull($result);
701
	}
702
 
703
/**
704
 * testLog method
705
 *
706
 * @outputBuffering enabled
707
 * @return void
708
 */
709
	public function testLog() {
710
		$this->testDb->logQuery('Query 1');
711
		$this->testDb->logQuery('Query 2');
712
 
713
		$log = $this->testDb->getLog(false, false);
714
		$result = Hash::extract($log['log'], '{n}.query');
715
		$expected = array('Query 1', 'Query 2');
716
		$this->assertEquals($expected, $result);
717
 
718
		$oldDebug = Configure::read('debug');
719
		Configure::write('debug', 2);
720
		ob_start();
721
		$this->testDb->showLog();
722
		$contents = ob_get_clean();
723
 
724
		$this->assertRegExp('/Query 1/s', $contents);
725
		$this->assertRegExp('/Query 2/s', $contents);
726
 
727
		ob_start();
728
		$this->testDb->showLog(true);
729
		$contents = ob_get_clean();
730
 
731
		$this->assertRegExp('/Query 1/s', $contents);
732
		$this->assertRegExp('/Query 2/s', $contents);
733
 
734
		Configure::write('debug', $oldDebug);
735
	}
736
 
737
/**
738
 * test getting the query log as an array.
739
 *
740
 * @return void
741
 */
742
	public function testGetLog() {
743
		$this->testDb->logQuery('Query 1');
744
		$this->testDb->logQuery('Query 2');
745
 
746
		$log = $this->testDb->getLog();
747
		$expected = array('query' => 'Query 1', 'params' => array(), 'affected' => '', 'numRows' => '', 'took' => '');
748
 
749
		$this->assertEquals($expected, $log['log'][0]);
750
		$expected = array('query' => 'Query 2', 'params' => array(), 'affected' => '', 'numRows' => '', 'took' => '');
751
		$this->assertEquals($expected, $log['log'][1]);
752
		$expected = array('query' => 'Error 1', 'affected' => '', 'numRows' => '', 'took' => '');
753
	}
754
 
755
/**
756
 * test getting the query log as an array, setting bind params.
757
 *
758
 * @return void
759
 */
760
	public function testGetLogParams() {
761
		$this->testDb->logQuery('Query 1', array(1, 2, 'abc'));
762
		$this->testDb->logQuery('Query 2', array('field1' => 1, 'field2' => 'abc'));
763
 
764
		$log = $this->testDb->getLog();
765
		$expected = array('query' => 'Query 1', 'params' => array(1, 2, 'abc'), 'affected' => '', 'numRows' => '', 'took' => '');
766
		$this->assertEquals($expected, $log['log'][0]);
767
		$expected = array('query' => 'Query 2', 'params' => array('field1' => 1, 'field2' => 'abc'), 'affected' => '', 'numRows' => '', 'took' => '');
768
		$this->assertEquals($expected, $log['log'][1]);
769
	}
770
 
771
/**
772
 * test that query() returns boolean values from operations like CREATE TABLE
773
 *
774
 * @return void
775
 */
776
	public function testFetchAllBooleanReturns() {
777
		$name = $this->db->fullTableName('test_query');
778
		$query = "CREATE TABLE {$name} (name varchar(10));";
779
		$result = $this->db->query($query);
780
		$this->assertTrue($result, 'Query did not return a boolean');
781
 
782
		$query = "DROP TABLE {$name};";
783
		$result = $this->db->query($query);
784
		$this->assertTrue($result, 'Query did not return a boolean');
785
	}
786
 
787
/**
788
 * test order to generate query order clause for virtual fields
789
 *
790
 * @return void
791
 */
792
	public function testVirtualFieldsInOrder() {
793
		$Article = ClassRegistry::init('Article');
794
		$Article->virtualFields = array(
795
			'this_moment' => 'NOW()',
796
			'two' => '1 + 1',
797
		);
798
		$order = array('two', 'this_moment');
799
		$result = $this->db->order($order, 'ASC', $Article);
800
		$expected = ' ORDER BY (1 + 1) ASC, (NOW()) ASC';
801
		$this->assertEquals($expected, $result);
802
 
803
		$order = array('Article.two', 'Article.this_moment');
804
		$result = $this->db->order($order, 'ASC', $Article);
805
		$expected = ' ORDER BY (1 + 1) ASC, (NOW()) ASC';
806
		$this->assertEquals($expected, $result);
807
	}
808
 
809
/**
810
 * test the permutations of fullTableName()
811
 *
812
 * @return void
813
 */
814
	public function testFullTablePermutations() {
815
		$Article = ClassRegistry::init('Article');
816
		$result = $this->testDb->fullTableName($Article, false, false);
817
		$this->assertEquals('articles', $result);
818
 
819
		$Article->tablePrefix = 'tbl_';
820
		$result = $this->testDb->fullTableName($Article, false, false);
821
		$this->assertEquals('tbl_articles', $result);
822
 
823
		$Article->useTable = $Article->table = 'with spaces';
824
		$Article->tablePrefix = '';
825
		$result = $this->testDb->fullTableName($Article, true, false);
826
		$this->assertEquals('`with spaces`', $result);
827
 
828
		$this->loadFixtures('Article');
829
		$Article->useTable = $Article->table = 'articles';
830
		$Article->setDataSource('test');
831
		$testdb = $Article->getDataSource();
832
		$result = $testdb->fullTableName($Article, false, true);
833
		$this->assertEquals($testdb->getSchemaName() . '.articles', $result);
834
 
835
		// tests for empty schemaName
836
		$noschema = ConnectionManager::create('noschema', array(
837
			'datasource' => 'DboTestSource'
838
			));
839
		$Article->setDataSource('noschema');
840
		$Article->schemaName = null;
841
		$result = $noschema->fullTableName($Article, false, true);
842
		$this->assertEquals('articles', $result);
843
 
844
		$this->testDb->config['prefix'] = 't_';
845
		$result = $this->testDb->fullTableName('post_tag', false, false);
846
		$this->assertEquals('t_post_tag', $result);
847
	}
848
 
849
/**
850
 * test that read() only calls queryAssociation on db objects when the method is defined.
851
 *
852
 * @return void
853
 */
854
	public function testReadOnlyCallingQueryAssociationWhenDefined() {
855
		$this->loadFixtures('Article', 'User', 'ArticlesTag', 'Tag');
856
		ConnectionManager::create('test_no_queryAssociation', array(
857
			'datasource' => 'MockDataSource'
858
		));
859
		$Article = ClassRegistry::init('Article');
860
		$Article->Comment->useDbConfig = 'test_no_queryAssociation';
861
		$result = $Article->find('all');
862
		$this->assertTrue(is_array($result));
863
	}
864
 
865
/**
866
 * test that queryAssociation() reuse already joined data for 'belongsTo' and 'hasOne' associations
867
 * instead of running unneeded queries for each record
868
 *
869
 * @return void
870
 */
871
	public function testQueryAssociationUnneededQueries() {
872
		$this->loadFixtures('Article', 'User', 'Comment', 'Attachment', 'Tag', 'ArticlesTag');
873
		$Comment = ClassRegistry::init('Comment');
874
 
875
		$fullDebug = $this->db->fullDebug;
876
		$this->db->fullDebug = true;
877
 
878
		$Comment->find('all', array('recursive' => 2)); // ensure Model descriptions are saved
879
		$this->db->getLog();
880
 
881
		// case: Comment belongsTo User and Article
882
		$Comment->unbindModel(array(
883
			'hasOne' => array('Attachment')
884
		));
885
		$Comment->Article->unbindModel(array(
886
			'belongsTo' => array('User'),
887
			'hasMany' => array('Comment'),
888
			'hasAndBelongsToMany' => array('Tag')
889
		));
890
		$Comment->find('all', array('recursive' => 2));
891
		$log = $this->db->getLog();
892
		$this->assertEquals(1, count($log['log']));
893
 
894
		// case: Comment belongsTo Article, Article belongsTo User
895
		$Comment->unbindModel(array(
896
			'belongsTo' => array('User'),
897
			'hasOne' => array('Attachment')
898
		));
899
		$Comment->Article->unbindModel(array(
900
			'hasMany' => array('Comment'),
901
			'hasAndBelongsToMany' => array('Tag'),
902
		));
903
		$Comment->find('all', array('recursive' => 2));
904
		$log = $this->db->getLog();
905
		$this->assertEquals(7, count($log['log']));
906
 
907
		// case: Comment hasOne Attachment
908
		$Comment->unbindModel(array(
909
			'belongsTo' => array('Article', 'User'),
910
		));
911
		$Comment->Attachment->unbindModel(array(
912
			'belongsTo' => array('Comment'),
913
		));
914
		$Comment->find('all', array('recursive' => 2));
915
		$log = $this->db->getLog();
916
		$this->assertEquals(1, count($log['log']));
917
 
918
		$this->db->fullDebug = $fullDebug;
919
	}
920
 
921
/**
922
 * Tests that generation association queries without LinkModel still works.
923
 * Mainly BC.
924
 *
925
 * @return void
926
 */
927
	public function testGenerateAssociationQuery() {
928
		$this->loadFixtures('Article');
929
		$Article = ClassRegistry::init('Article');
930
 
931
		$queryData = array(
932
			'conditions' => array(
933
				'Article.id' => 1
934
			),
935
			'fields' => array(
936
				'Article.id',
937
				'Article.title',
938
			),
939
			'joins' => array(),
940
			'limit' => 2,
941
			'offset' => 2,
942
			'order' => array('title'),
943
			'page' => 2,
944
			'group' => null,
945
			'callbacks' => 1
946
		);
947
 
948
		$result = $this->db->generateAssociationQuery($Article, null, null, null, null, $queryData, false);
949
		$this->assertContains('SELECT', $result);
950
		$this->assertContains('FROM', $result);
951
		$this->assertContains('WHERE', $result);
952
		$this->assertContains('ORDER', $result);
953
	}
954
 
955
/**
956
 * test that fields() is using methodCache()
957
 *
958
 * @return void
959
 */
960
	public function testFieldsUsingMethodCache() {
961
		$this->testDb->cacheMethods = false;
962
		DboTestSource::$methodCache = array();
963
 
964
		$Article = ClassRegistry::init('Article');
965
		$this->testDb->fields($Article, null, array('title', 'body', 'published'));
966
		$this->assertTrue(empty(DboTestSource::$methodCache['fields']), 'Cache not empty');
967
	}
968
 
969
/**
970
 * test that fields() method cache detects datasource changes
971
 *
972
 * @return void
973
 */
974
	public function testFieldsCacheKeyWithDatasourceChange() {
975
		ConnectionManager::create('firstschema', array(
976
			'datasource' => 'DboTestSource'
977
		));
978
		ConnectionManager::create('secondschema', array(
979
			'datasource' => 'DboSecondTestSource'
980
		));
981
		Cache::delete('method_cache', '_cake_core_');
982
		DboTestSource::$methodCache = array();
983
		$Article = ClassRegistry::init('Article');
984
 
985
		$Article->setDataSource('firstschema');
986
		$ds = $Article->getDataSource();
987
		$ds->cacheMethods = true;
988
		$first = $ds->fields($Article, null, array('title', 'body', 'published'));
989
 
990
		$Article->setDataSource('secondschema');
991
		$ds = $Article->getDataSource();
992
		$ds->cacheMethods = true;
993
		$second = $ds->fields($Article, null, array('title', 'body', 'published'));
994
 
995
		$this->assertNotEquals($first, $second);
996
		$this->assertEquals(2, count(DboTestSource::$methodCache['fields']));
997
	}
998
 
999
/**
1000
 * test that fields() method cache detects schema name changes
1001
 *
1002
 * @return void
1003
 */
1004
	public function testFieldsCacheKeyWithSchemanameChange() {
1005
		if ($this->db instanceof Postgres || $this->db instanceof Sqlserver) {
1006
			$this->markTestSkipped('Cannot run this test with SqlServer or Postgres');
1007
		}
1008
		Cache::delete('method_cache', '_cake_core_');
1009
		DboSource::$methodCache = array();
1010
		$Article = ClassRegistry::init('Article');
1011
 
1012
		$ds = $Article->getDataSource();
1013
		$ds->cacheMethods = true;
1014
		$first = $ds->fields($Article);
1015
 
1016
		$Article->schemaName = 'secondSchema';
1017
		$ds = $Article->getDataSource();
1018
		$ds->cacheMethods = true;
1019
		$second = $ds->fields($Article);
1020
 
1021
		$this->assertEquals(2, count(DboSource::$methodCache['fields']));
1022
	}
1023
 
1024
/**
1025
 * Test that group works without a model
1026
 *
1027
 * @return void
1028
 */
1029
	public function testGroupNoModel() {
1030
		$result = $this->db->group('created');
1031
		$this->assertEquals(' GROUP BY created', $result);
1032
	}
1033
 
1034
/**
1035
 * Test getting the last error.
1036
 *
1037
 * @return void
1038
 */
1039
	public function testLastError() {
1040
		$stmt = $this->getMock('PDOStatement');
1041
		$stmt->expects($this->any())
1042
			->method('errorInfo')
1043
			->will($this->returnValue(array('', 'something', 'bad')));
1044
 
1045
		$result = $this->db->lastError($stmt);
1046
		$expected = 'something: bad';
1047
		$this->assertEquals($expected, $result);
1048
	}
1049
 
1050
/**
1051
 * Tests that transaction commands are logged
1052
 *
1053
 * @return void
1054
 */
1055
	public function testTransactionLogging() {
1056
		$conn = $this->getMock('MockPDO');
1057
		$db = new DboTestSource();
1058
		$db->setConnection($conn);
1059
		$conn->expects($this->exactly(2))->method('beginTransaction')
1060
			->will($this->returnValue(true));
1061
		$conn->expects($this->once())->method('commit')->will($this->returnValue(true));
1062
		$conn->expects($this->once())->method('rollback')->will($this->returnValue(true));
1063
 
1064
		$db->begin();
1065
		$log = $db->getLog();
1066
		$expected = array('query' => 'BEGIN', 'params' => array(), 'affected' => '', 'numRows' => '', 'took' => '');
1067
		$this->assertEquals($expected, $log['log'][0]);
1068
 
1069
		$db->commit();
1070
		$expected = array('query' => 'COMMIT', 'params' => array(), 'affected' => '', 'numRows' => '', 'took' => '');
1071
		$log = $db->getLog();
1072
		$this->assertEquals($expected, $log['log'][0]);
1073
 
1074
		$db->begin();
1075
		$expected = array('query' => 'BEGIN', 'params' => array(), 'affected' => '', 'numRows' => '', 'took' => '');
1076
		$log = $db->getLog();
1077
		$this->assertEquals($expected, $log['log'][0]);
1078
 
1079
		$db->rollback();
1080
		$expected = array('query' => 'ROLLBACK', 'params' => array(), 'affected' => '', 'numRows' => '', 'took' => '');
1081
		$log = $db->getLog();
1082
		$this->assertEquals($expected, $log['log'][0]);
1083
	}
1084
 
1085
/**
1086
 * Test nested transaction calls
1087
 *
1088
 * @return void
1089
 */
1090
	public function testTransactionNested() {
1091
		$conn = $this->getMock('MockPDO');
1092
		$db = new DboTestSource();
1093
		$db->setConnection($conn);
1094
		$db->useNestedTransactions = true;
1095
		$db->nestedSupport = true;
1096
 
1097
		$conn->expects($this->at(0))->method('beginTransaction')->will($this->returnValue(true));
1098
		$conn->expects($this->at(1))->method('exec')->with($this->equalTo('SAVEPOINT LEVEL1'))->will($this->returnValue(true));
1099
		$conn->expects($this->at(2))->method('exec')->with($this->equalTo('RELEASE SAVEPOINT LEVEL1'))->will($this->returnValue(true));
1100
		$conn->expects($this->at(3))->method('exec')->with($this->equalTo('SAVEPOINT LEVEL1'))->will($this->returnValue(true));
1101
		$conn->expects($this->at(4))->method('exec')->with($this->equalTo('ROLLBACK TO SAVEPOINT LEVEL1'))->will($this->returnValue(true));
1102
		$conn->expects($this->at(5))->method('commit')->will($this->returnValue(true));
1103
 
1104
		$this->_runTransactions($db);
1105
	}
1106
 
1107
/**
1108
 * Test nested transaction calls without support
1109
 *
1110
 * @return void
1111
 */
1112
	public function testTransactionNestedWithoutSupport() {
1113
		$conn = $this->getMock('MockPDO');
1114
		$db = new DboTestSource();
1115
		$db->setConnection($conn);
1116
		$db->useNestedTransactions = true;
1117
		$db->nestedSupport = false;
1118
 
1119
		$conn->expects($this->once())->method('beginTransaction')->will($this->returnValue(true));
1120
		$conn->expects($this->never())->method('exec');
1121
		$conn->expects($this->once())->method('commit')->will($this->returnValue(true));
1122
 
1123
		$this->_runTransactions($db);
1124
	}
1125
 
1126
/**
1127
 * Test nested transaction disabled
1128
 *
1129
 * @return void
1130
 */
1131
	public function testTransactionNestedDisabled() {
1132
		$conn = $this->getMock('MockPDO');
1133
		$db = new DboTestSource();
1134
		$db->setConnection($conn);
1135
		$db->useNestedTransactions = false;
1136
		$db->nestedSupport = true;
1137
 
1138
		$conn->expects($this->once())->method('beginTransaction')->will($this->returnValue(true));
1139
		$conn->expects($this->never())->method('exec');
1140
		$conn->expects($this->once())->method('commit')->will($this->returnValue(true));
1141
 
1142
		$this->_runTransactions($db);
1143
	}
1144
 
1145
/**
1146
 * Nested transaction calls
1147
 *
1148
 * @param DboTestSource $db
1149
 * @return void
1150
 */
1151
	protected function _runTransactions($db) {
1152
		$db->begin();
1153
		$db->begin();
1154
		$db->commit();
1155
		$db->begin();
1156
		$db->rollback();
1157
		$db->commit();
1158
	}
1159
 
1160
/**
1161
 * Test build statement with some fields missing
1162
 *
1163
 * @return void
1164
 */
1165
	public function testBuildStatementDefaults() {
1166
		$conn = $this->getMock('MockPDO', array('quote'));
1167
		$conn->expects($this->at(0))
1168
			->method('quote')
1169
			->will($this->returnValue('foo bar'));
1170
		$db = new DboTestSource();
1171
		$db->setConnection($conn);
1172
		$subQuery = $db->buildStatement(
1173
			array(
1174
				'fields' => array('DISTINCT(AssetsTag.asset_id)'),
1175
				'table' => "assets_tags",
1176
				'alias' => "AssetsTag",
1177
				'conditions' => array("Tag.name" => 'foo bar'),
1178
				'limit' => null,
1179
				'group' => "AssetsTag.asset_id"
1180
			),
1181
			$this->Model
1182
		);
1183
		$expected = 'SELECT DISTINCT(AssetsTag.asset_id) FROM assets_tags AS AssetsTag   WHERE Tag.name = foo bar  GROUP BY AssetsTag.asset_id';
1184
		$this->assertEquals($expected, $subQuery);
1185
	}
1186
 
1187
/**
1188
 * data provider for testBuildJoinStatement
1189
 *
1190
 * @return array
1191
 */
1192
	public static function joinStatements() {
1193
		return array(
1194
			array(array(
1195
				'type' => 'CROSS',
1196
				'alias' => 'PostsTag',
1197
				'table' => 'posts_tags',
1198
				'conditions' => array('1 = 1')
1199
			), 'CROSS JOIN cakephp.posts_tags AS PostsTag'),
1200
			array(array(
1201
				'type' => 'LEFT',
1202
				'alias' => 'PostsTag',
1203
				'table' => 'posts_tags',
1204
			), 'LEFT JOIN cakephp.posts_tags AS PostsTag'),
1205
			array(array(
1206
				'type' => 'LEFT',
1207
				'alias' => 'PostsTag',
1208
				'table' => 'posts_tags',
1209
				'conditions' => array('PostsTag.post_id = Post.id')
1210
			), 'LEFT JOIN cakephp.posts_tags AS PostsTag ON (PostsTag.post_id = Post.id)'),
1211
			array(array(
1212
				'type' => 'LEFT',
1213
				'alias' => 'Stock',
1214
				'table' => '(SELECT Stock.article_id, sum(quantite) quantite FROM stocks AS Stock GROUP BY Stock.article_id)',
1215
				'conditions' => 'Stock.article_id = Article.id'
1216
			), 'LEFT JOIN (SELECT Stock.article_id, sum(quantite) quantite FROM stocks AS Stock GROUP BY Stock.article_id) AS Stock ON (Stock.article_id = Article.id)')
1217
		);
1218
	}
1219
 
1220
/**
1221
 * Test buildJoinStatement()
1222
 * ensure that schemaName is not added when table value is a subquery
1223
 *
1224
 * @dataProvider joinStatements
1225
 * @return void
1226
 */
1227
	public function testBuildJoinStatement($join, $expected) {
1228
		$db = $this->getMock('DboTestSource', array('getSchemaName'));
1229
		$db->expects($this->any())
1230
			->method('getSchemaName')
1231
			->will($this->returnValue('cakephp'));
1232
		$result = $db->buildJoinStatement($join);
1233
		$this->assertEquals($expected, $result);
1234
	}
1235
 
1236
/**
1237
 * data provider for testBuildJoinStatementWithTablePrefix
1238
 *
1239
 * @return array
1240
 */
1241
	public static function joinStatementsWithPrefix($schema) {
1242
		return array(
1243
			array(array(
1244
				'type' => 'LEFT',
1245
				'alias' => 'PostsTag',
1246
				'table' => 'posts_tags',
1247
				'conditions' => array('PostsTag.post_id = Post.id')
1248
			), 'LEFT JOIN pre_posts_tags AS PostsTag ON (PostsTag.post_id = Post.id)'),
1249
				array(array(
1250
					'type' => 'LEFT',
1251
					'alias' => 'Stock',
1252
					'table' => '(SELECT Stock.article_id, sum(quantite) quantite FROM stocks AS Stock GROUP BY Stock.article_id)',
1253
					'conditions' => 'Stock.article_id = Article.id'
1254
				), 'LEFT JOIN (SELECT Stock.article_id, sum(quantite) quantite FROM stocks AS Stock GROUP BY Stock.article_id) AS Stock ON (Stock.article_id = Article.id)')
1255
			);
1256
	}
1257
 
1258
/**
1259
 * Test buildJoinStatement()
1260
 * ensure that prefix is not added when table value is a subquery
1261
 *
1262
 * @dataProvider joinStatementsWithPrefix
1263
 * @return void
1264
 */
1265
	public function testBuildJoinStatementWithTablePrefix($join, $expected) {
1266
		$db = new DboTestSource();
1267
		$db->config['prefix'] = 'pre_';
1268
		$result = $db->buildJoinStatement($join);
1269
		$this->assertEquals($expected, $result);
1270
	}
1271
 
1272
/**
1273
 * Test conditionKeysToString()
1274
 *
1275
 * @return void
1276
 */
1277
	public function testConditionKeysToString() {
1278
		$Article = ClassRegistry::init('Article');
1279
		$conn = $this->getMock('MockPDO', array('quote'));
1280
		$db = new DboTestSource();
1281
		$db->setConnection($conn);
1282
 
1283
		$conn->expects($this->at(0))
1284
			->method('quote')
1285
			->will($this->returnValue('just text'));
1286
 
1287
		$conditions = array('Article.name' => 'just text');
1288
		$result = $db->conditionKeysToString($conditions, true, $Article);
1289
		$expected = "Article.name = just text";
1290
		$this->assertEquals($expected, $result[0]);
1291
 
1292
		$conn->expects($this->at(0))
1293
			->method('quote')
1294
			->will($this->returnValue('just text'));
1295
		$conn->expects($this->at(1))
1296
			->method('quote')
1297
			->will($this->returnValue('other text'));
1298
 
1299
		$conditions = array('Article.name' => array('just text', 'other text'));
1300
		$result = $db->conditionKeysToString($conditions, true, $Article);
1301
		$expected = "Article.name IN (just text, other text)";
1302
		$this->assertEquals($expected, $result[0]);
1303
	}
1304
 
1305
/**
1306
 * Test conditionKeysToString() with virtual field
1307
 *
1308
 * @return void
1309
 */
1310
	public function testConditionKeysToStringVirtualField() {
1311
		$Article = ClassRegistry::init('Article');
1312
		$Article->virtualFields = array(
1313
			'extra' => 'something virtual'
1314
		);
1315
		$conn = $this->getMock('MockPDO', array('quote'));
1316
		$db = new DboTestSource();
1317
		$db->setConnection($conn);
1318
 
1319
		$conn->expects($this->at(0))
1320
			->method('quote')
1321
			->will($this->returnValue('just text'));
1322
 
1323
		$conditions = array('Article.extra' => 'just text');
1324
		$result = $db->conditionKeysToString($conditions, true, $Article);
1325
		$expected = "(" . $Article->virtualFields['extra'] . ") = just text";
1326
		$this->assertEquals($expected, $result[0]);
1327
 
1328
		$conn->expects($this->at(0))
1329
			->method('quote')
1330
			->will($this->returnValue('just text'));
1331
		$conn->expects($this->at(1))
1332
			->method('quote')
1333
			->will($this->returnValue('other text'));
1334
 
1335
		$conditions = array('Article.extra' => array('just text', 'other text'));
1336
		$result = $db->conditionKeysToString($conditions, true, $Article);
1337
		$expected = "(" . $Article->virtualFields['extra'] . ") IN (just text, other text)";
1338
		$this->assertEquals($expected, $result[0]);
1339
	}
1340
 
1341
/**
1342
 * Test the limit function.
1343
 *
1344
 * @return void
1345
 */
1346
	public function testLimit() {
1347
		$db = new DboTestSource();
1348
 
1349
		$result = $db->limit('0');
1350
		$this->assertNull($result);
1351
 
1352
		$result = $db->limit('10');
1353
		$this->assertEquals(' LIMIT 10', $result);
1354
 
1355
		$result = $db->limit('FARTS', 'BOOGERS');
1356
		$this->assertEquals(' LIMIT 0, 0', $result);
1357
 
1358
		$result = $db->limit(20, 10);
1359
		$this->assertEquals(' LIMIT 10, 20', $result);
1360
 
1361
		$result = $db->limit(10, 300000000000000000000000000000);
1362
		$scientificNotation = sprintf('%.1E', 300000000000000000000000000000);
1363
		$this->assertNotContains($scientificNotation, $result);
1364
	}
1365
 
1366
/**
1367
 * Test insertMulti with id position.
1368
 *
1369
 * @return void
1370
 */
1371
	public function testInsertMultiId() {
1372
		$this->loadFixtures('Article');
1373
		$Article = ClassRegistry::init('Article');
1374
		$db = $Article->getDatasource();
1375
		$datetime = date('Y-m-d H:i:s');
1376
		$data = array(
1377
			array(
1378
				'user_id' => 1,
1379
				'title' => 'test',
1380
				'body' => 'test',
1381
				'published' => 'N',
1382
				'created' => $datetime,
1383
				'updated' => $datetime,
1384
				'id' => 100,
1385
			),
1386
			array(
1387
				'user_id' => 1,
1388
				'title' => 'test 101',
1389
				'body' => 'test 101',
1390
				'published' => 'N',
1391
				'created' => $datetime,
1392
				'updated' => $datetime,
1393
				'id' => 101,
1394
			)
1395
		);
1396
		$result = $db->insertMulti('articles', array_keys($data[0]), $data);
1397
		$this->assertTrue($result, 'Data was saved');
1398
 
1399
		$data = array(
1400
			array(
1401
				'id' => 102,
1402
				'user_id' => 1,
1403
				'title' => 'test',
1404
				'body' => 'test',
1405
				'published' => 'N',
1406
				'created' => $datetime,
1407
				'updated' => $datetime,
1408
			),
1409
			array(
1410
				'id' => 103,
1411
				'user_id' => 1,
1412
				'title' => 'test 101',
1413
				'body' => 'test 101',
1414
				'published' => 'N',
1415
				'created' => $datetime,
1416
				'updated' => $datetime,
1417
			)
1418
		);
1419
 
1420
		$result = $db->insertMulti('articles', array_keys($data[0]), $data);
1421
		$this->assertTrue($result, 'Data was saved');
1422
	}
1423
 
1424
/**
1425
 * Test defaultConditions()
1426
 *
1427
 * @return void
1428
 */
1429
	public function testDefaultConditions() {
1430
		$this->loadFixtures('Article');
1431
		$Article = ClassRegistry::init('Article');
1432
		$db = $Article->getDataSource();
1433
 
1434
		// Creates a default set of conditions from the model if $conditions is null/empty.
1435
		$Article->id = 1;
1436
		$result = $db->defaultConditions($Article, null);
1437
		$this->assertEquals(array('Article.id' => 1), $result);
1438
 
1439
		// $useAlias == false
1440
		$Article->id = 1;
1441
		$result = $db->defaultConditions($Article, null, false);
1442
		$this->assertEquals(array($db->fullTableName($Article, false) . '.id' => 1), $result);
1443
 
1444
		// If conditions are supplied then they will be returned.
1445
		$Article->id = 1;
1446
		$result = $db->defaultConditions($Article, array('Article.title' => 'First article'));
1447
		$this->assertEquals(array('Article.title' => 'First article'), $result);
1448
 
1449
		// If a model doesn't exist and no conditions were provided either null or false will be returned based on what was input.
1450
		$Article->id = 1000000;
1451
		$result = $db->defaultConditions($Article, null);
1452
		$this->assertNull($result);
1453
 
1454
		$Article->id = 1000000;
1455
		$result = $db->defaultConditions($Article, false);
1456
		$this->assertFalse($result);
1457
 
1458
		// Safe update mode
1459
		$Article->id = 1000000;
1460
		$Article->__safeUpdateMode = true;
1461
		$result = $db->defaultConditions($Article, null);
1462
		$this->assertFalse($result);
1463
	}
1464
 
1465
/**
1466
 * Test that count how many times afterFind is called
1467
 *
1468
 * @return void
1469
 */
1470
	public function testCountAfterFindCalls() {
1471
		$this->loadFixtures('Article', 'User', 'Comment', 'Attachment', 'Tag', 'ArticlesTag');
1472
 
1473
		// Use alias to make testing "primary = true" easy
1474
		$Primary = $this->getMock('Comment', array('afterFind'), array(array('alias' => 'Primary')), '', true);
1475
 
1476
		$Article = $this->getMock('Article', array('afterFind'), array(), '', true);
1477
		$User = $this->getMock('User', array('afterFind'), array(), '', true);
1478
		$Comment = $this->getMock('Comment', array('afterFind'), array(), '', true);
1479
		$Tag = $this->getMock('Tag', array('afterFind'), array(), '', true);
1480
		$Attachment = $this->getMock('Attachment', array('afterFind'), array(), '', true);
1481
 
1482
		$Primary->Article = $Article;
1483
		$Primary->Article->User = $User;
1484
		$Primary->Article->Tag = $Tag;
1485
		$Primary->Article->Comment = $Comment;
1486
		$Primary->Attachment = $Attachment;
1487
		$Primary->Attachment->Comment = $Comment;
1488
		$Primary->User = $User;
1489
 
1490
		// primary = true
1491
		$Primary->expects($this->once())
1492
			->method('afterFind')->with($this->anything(), $this->isTrue())->will($this->returnArgument(0));
1493
 
1494
		// primary = false
1495
		$Article->expects($this->once()) // Primary belongs to 1 Article
1496
			->method('afterFind')->with($this->anything(), $this->isFalse())->will($this->returnArgument(0));
1497
		$User->expects($this->exactly(2)) // Article belongs to 1 User and Primary belongs to 1 User
1498
			->method('afterFind')->with($this->anything(), $this->isFalse())->will($this->returnArgument(0));
1499
		$Tag->expects($this->exactly(2)) // Article has 2 Tags
1500
			->method('afterFind')->with($this->anything(), $this->isFalse())->will($this->returnArgument(0));
1501
		$Comment->expects($this->exactly(3)) // Article has 2 Comments and Attachment belongs to 1 Comment
1502
			->method('afterFind')->with($this->anything(), $this->isFalse())->will($this->returnArgument(0));
1503
		$Attachment->expects($this->once()) // Primary has 1 Attachment
1504
			->method('afterFind')->with($this->anything(), $this->isFalse())->will($this->returnArgument(0));
1505
 
1506
		$result = $Primary->find('first', array('conditions' => array('Primary.id' => 5), 'recursive' => 2));
1507
		$this->assertCount(2, $result['Article']['Tag']);
1508
		$this->assertCount(2, $result['Article']['Comment']);
1509
 
1510
		// hasMany special case
1511
		// Both User and Article has many Comments
1512
		$User = $this->getMock('User', array('afterFind'), array(), '', true);
1513
		$Article = $this->getMock('Article', array('afterFind'), array(), '', true);
1514
		$Comment = $this->getMock('Comment', array('afterFind'), array(), '', true);
1515
 
1516
		$User->bindModel(array('hasMany' => array('Comment', 'Article')));
1517
		$Article->unbindModel(array('belongsTo' => array('User'), 'hasAndBelongsToMany' => array('Tag')));
1518
		$Comment->unbindModel(array('belongsTo' => array('User', 'Article'), 'hasOne' => 'Attachment'));
1519
 
1520
		$User->Comment = $Comment;
1521
		$User->Article = $Article;
1522
		$User->Article->Comment = $Comment;
1523
 
1524
		// primary = true
1525
		$User->expects($this->once())
1526
			->method('afterFind')->with($this->anything(), $this->isTrue())->will($this->returnArgument(0));
1527
 
1528
		$Article->expects($this->exactly(2)) // User has 2 Articles
1529
			->method('afterFind')->with($this->anything(), $this->isFalse())->will($this->returnArgument(0));
1530
 
1531
		$Comment->expects($this->exactly(7)) // User1 has 3 Comments, Article[id=1] has 4 Comments and Article[id=3] has 0 Comments
1532
			->method('afterFind')->with($this->anything(), $this->isFalse())->will($this->returnArgument(0));
1533
 
1534
		$result = $User->find('first', array('conditions' => array('User.id' => 1), 'recursive' => 2));
1535
		$this->assertCount(3, $result['Comment']);
1536
		$this->assertCount(2, $result['Article']);
1537
		$this->assertCount(4, $result['Article'][0]['Comment']);
1538
		$this->assertCount(0, $result['Article'][1]['Comment']);
1539
	}
1540
 
1541
/**
1542
 * Test format of $results in afterFind
1543
 *
1544
 * @return void
1545
 */
1546
	public function testUseConsistentAfterFind() {
1547
		$this->loadFixtures('Author', 'Post');
1548
 
1549
		$expected = array(
1550
			'Author' => array(
1551
				'id' => '1',
1552
				'user' => 'mariano',
1553
				'password' => '5f4dcc3b5aa765d61d8327deb882cf99',
1554
				'created' => '2007-03-17 01:16:23',
1555
				'updated' => '2007-03-17 01:18:31',
1556
				'test' => 'working',
1557
			),
1558
			'Post' => array(
1559
				array(
1560
					'id' => '1',
1561
					'author_id' => '1',
1562
					'title' => 'First Post',
1563
					'body' => 'First Post Body',
1564
					'published' => 'Y',
1565
					'created' => '2007-03-18 10:39:23',
1566
					'updated' => '2007-03-18 10:41:31',
1567
				),
1568
				array(
1569
					'id' => '3',
1570
					'author_id' => '1',
1571
					'title' => 'Third Post',
1572
					'body' => 'Third Post Body',
1573
					'published' => 'Y',
1574
					'created' => '2007-03-18 10:43:23',
1575
					'updated' => '2007-03-18 10:45:31',
1576
				),
1577
			),
1578
		);
1579
 
1580
		$Author = new Author();
1581
		$Post = $this->getMock('Post', array('afterFind'), array(), '', true);
1582
		$Post->expects($this->at(0))->method('afterFind')->with(array(array('Post' => $expected['Post'][0])), $this->isFalse())->will($this->returnArgument(0));
1583
		$Post->expects($this->at(1))->method('afterFind')->with(array(array('Post' => $expected['Post'][1])), $this->isFalse())->will($this->returnArgument(0));
1584
 
1585
		$Author->bindModel(array('hasMany' => array('Post' => array('limit' => 2, 'order' => 'Post.id'))));
1586
		$Author->Post = $Post;
1587
 
1588
		$result = $Author->find('first', array('conditions' => array('Author.id' => 1), 'recursive' => 1));
1589
		$this->assertEquals($expected, $result);
1590
 
1591
		// Backward compatiblity
1592
		$Author = new Author();
1593
		$Post = $this->getMock('Post', array('afterFind'), array(), '', true);
1594
		$Post->expects($this->once())->method('afterFind')->with($expected['Post'], $this->isFalse())->will($this->returnArgument(0));
1595
		$Post->useConsistentAfterFind = false;
1596
 
1597
		$Author->bindModel(array('hasMany' => array('Post' => array('limit' => 2, 'order' => 'Post.id'))));
1598
		$Author->Post = $Post;
1599
 
1600
		$result = $Author->find('first', array('conditions' => array('Author.id' => 1), 'recursive' => 1));
1601
		$this->assertEquals($expected, $result);
1602
	}
1603
 
1604
/**
1605
 * Test that afterFind is called correctly for 'joins'
1606
 *
1607
 * @return void
1608
 */
1609
	public function testJoinsAfterFind() {
1610
		$this->loadFixtures('Article', 'User');
1611
 
1612
		$User = new User();
1613
		$User->bindModel(array('hasOne' => array('Article')));
1614
 
1615
		$Article = $this->getMock('Article', array('afterFind'), array(), '', true);
1616
		$Article->expects($this->once())
1617
			->method('afterFind')
1618
			->with(
1619
				array(
1620
 
1621
						'Article' => array(
1622
							'id' => '1',
1623
							'user_id' => '1',
1624
							'title' => 'First Article',
1625
							'body' => 'First Article Body',
1626
							'published' => 'Y',
1627
							'created' => '2007-03-18 10:39:23',
1628
							'updated' => '2007-03-18 10:41:31'
1629
						)
1630
					)
1631
				),
1632
				$this->isFalse()
1633
			)
1634
			->will($this->returnArgument(0));
1635
 
1636
		$User->Article = $Article;
1637
		$User->find('first', array(
1638
			'fields' => array(
1639
				'Article.id',
1640
				'Article.user_id',
1641
				'Article.title',
1642
				'Article.body',
1643
				'Article.published',
1644
				'Article.created',
1645
				'Article.updated'
1646
			),
1647
			'conditions' => array('User.id' => 1),
1648
			'recursive' => -1,
1649
			'joins' => array(
1650
				array(
1651
					'table' => 'articles',
1652
					'alias' => 'Article',
1653
					'type' => 'LEFT',
1654
					'conditions' => array(
1655
						'Article.user_id = User.id'
1656
					),
1657
				)
1658
			),
1659
			'order' => array('Article.id')
1660
		));
1661
	}
1662
 
1663
/**
1664
 * Test that afterFind is called correctly for 'hasOne' association.
1665
 *
1666
 * @return void
1667
 */
1668
	public function testHasOneAfterFind() {
1669
		$this->loadFixtures('Article', 'User', 'Comment');
1670
 
1671
		$User = new User();
1672
		$User->bindModel(array('hasOne' => array('Article')));
1673
 
1674
		$Article = $this->getMock('Article', array('afterFind'), array(), '', true);
1675
		$Article->unbindModel(array(
1676
			'belongsTo' => array('User'),
1677
			'hasMany' => array('Comment'),
1678
			'hasAndBelongsToMany' => array('Tag')
1679
		));
1680
		$Article->bindModel(array(
1681
			'hasOne' => array('Comment'),
1682
		));
1683
		$Article->expects($this->once())
1684
			->method('afterFind')
1685
			->with(
1686
				$this->equalTo(
1687
					array(
1688
 
1689
							'Article' => array(
1690
								'id' => '1',
1691
								'user_id' => '1',
1692
								'title' => 'First Article',
1693
								'body' => 'First Article Body',
1694
								'published' => 'Y',
1695
								'created' => '2007-03-18 10:39:23',
1696
								'updated' => '2007-03-18 10:41:31',
1697
								'Comment' => array(
1698
									'id' => '1',
1699
									'article_id' => '1',
1700
									'user_id' => '2',
1701
									'comment' => 'First Comment for First Article',
1702
									'published' => 'Y',
1703
									'created' => '2007-03-18 10:45:23',
1704
									'updated' => '2007-03-18 10:47:31',
1705
								)
1706
							)
1707
						)
1708
					)
1709
				),
1710
				$this->isFalse()
1711
			)
1712
			->will($this->returnArgument(0));
1713
 
1714
		$User->Article = $Article;
1715
		$User->find('first', array('conditions' => array('User.id' => 1), 'recursive' => 2));
1716
	}
1717
}