Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
13532 anikendra 1
<?php
2
/**
3
 * DboMysqlTest file
4
 *
5
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
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://cakephp.org CakePHP(tm) Project
14
 * @package       Cake.Test.Case.Model.Datasource.Database
15
 * @since         CakePHP(tm) v 1.2.0
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('Mysql', 'Model/Datasource/Database');
22
App::uses('CakeSchema', 'Model');
23
 
24
require_once dirname(dirname(dirname(__FILE__))) . DS . 'models.php';
25
 
26
/**
27
 * DboMysqlTest class
28
 *
29
 * @package       Cake.Test.Case.Model.Datasource.Database
30
 */
31
class MysqlTest extends CakeTestCase {
32
 
33
/**
34
 * autoFixtures property
35
 *
36
 * @var boolean
37
 */
38
	public $autoFixtures = false;
39
 
40
/**
41
 * fixtures property
42
 *
43
 * @var array
44
 */
45
	public $fixtures = array(
46
		'core.apple', 'core.article', 'core.articles_tag', 'core.attachment', 'core.comment',
47
		'core.sample', 'core.tag', 'core.user', 'core.post', 'core.author', 'core.data_test',
48
		'core.binary_test', 'core.inno'
49
	);
50
 
51
/**
52
 * The Dbo instance to be tested
53
 *
54
 * @var DboSource
55
 */
56
	public $Dbo = null;
57
 
58
/**
59
 * Sets up a Dbo class instance for testing
60
 *
61
 */
62
	public function setUp() {
63
		parent::setUp();
64
		$this->Dbo = ConnectionManager::getDataSource('test');
65
		if (!($this->Dbo instanceof Mysql)) {
66
			$this->markTestSkipped('The MySQL extension is not available.');
67
		}
68
		$this->_debug = Configure::read('debug');
69
		Configure::write('debug', 1);
70
		$this->model = ClassRegistry::init('MysqlTestModel');
71
	}
72
 
73
/**
74
 * Sets up a Dbo class instance for testing
75
 *
76
 */
77
	public function tearDown() {
78
		parent::tearDown();
79
		unset($this->model);
80
		ClassRegistry::flush();
81
		Configure::write('debug', $this->_debug);
82
	}
83
 
84
/**
85
 * Test Dbo value method
86
 *
87
 * @group quoting
88
 */
89
	public function testQuoting() {
90
		$result = $this->Dbo->fields($this->model);
91
		$expected = array(
92
			'`MysqlTestModel`.`id`',
93
			'`MysqlTestModel`.`client_id`',
94
			'`MysqlTestModel`.`name`',
95
			'`MysqlTestModel`.`login`',
96
			'`MysqlTestModel`.`passwd`',
97
			'`MysqlTestModel`.`addr_1`',
98
			'`MysqlTestModel`.`addr_2`',
99
			'`MysqlTestModel`.`zip_code`',
100
			'`MysqlTestModel`.`city`',
101
			'`MysqlTestModel`.`country`',
102
			'`MysqlTestModel`.`phone`',
103
			'`MysqlTestModel`.`fax`',
104
			'`MysqlTestModel`.`url`',
105
			'`MysqlTestModel`.`email`',
106
			'`MysqlTestModel`.`comments`',
107
			'`MysqlTestModel`.`last_login`',
108
			'`MysqlTestModel`.`created`',
109
			'`MysqlTestModel`.`updated`'
110
		);
111
		$this->assertEquals($expected, $result);
112
 
113
		$expected = 1.2;
114
		$result = $this->Dbo->value(1.2, 'float');
115
		$this->assertEquals($expected, $result);
116
 
117
		$expected = "'1,2'";
118
		$result = $this->Dbo->value('1,2', 'float');
119
		$this->assertEquals($expected, $result);
120
 
121
		$expected = "'4713e29446'";
122
		$result = $this->Dbo->value('4713e29446');
123
 
124
		$this->assertEquals($expected, $result);
125
 
126
		$expected = 'NULL';
127
		$result = $this->Dbo->value('', 'integer');
128
		$this->assertEquals($expected, $result);
129
 
130
		$expected = "'0'";
131
		$result = $this->Dbo->value('', 'boolean');
132
		$this->assertEquals($expected, $result);
133
 
134
		$expected = 10010001;
135
		$result = $this->Dbo->value(10010001);
136
		$this->assertEquals($expected, $result);
137
 
138
		$expected = "'00010010001'";
139
		$result = $this->Dbo->value('00010010001');
140
		$this->assertEquals($expected, $result);
141
	}
142
 
143
/**
144
 * test that localized floats don't cause trouble.
145
 *
146
 * @group quoting
147
 * @return void
148
 */
149
	public function testLocalizedFloats() {
150
		$this->skipIf(DS === '\\', 'The locale is not supported in Windows and affect the others tests.');
151
 
152
		$restore = setlocale(LC_NUMERIC, 0);
153
 
154
		$this->skipIf(setlocale(LC_NUMERIC, 'de_DE') === false, "The German locale isn't available.");
155
 
156
		$result = $this->Dbo->value(3.141593);
157
		$this->assertEquals('3.141593', $result);
158
 
159
		$result = $this->db->value(3.141593, 'float');
160
		$this->assertEquals('3.141593', $result);
161
 
162
		$result = $this->db->value(1234567.11, 'float');
163
		$this->assertEquals('1234567.11', $result);
164
 
165
		$result = $this->db->value(123456.45464748, 'float');
166
		$this->assertContains('123456.454647', $result);
167
 
168
		$result = $this->db->value(0.987654321, 'float');
169
		$this->assertEquals('0.987654321', (string)$result);
170
 
171
		$result = $this->db->value(2.2E-54, 'float');
172
		$this->assertEquals('2.2E-54', (string)$result);
173
 
174
		$result = $this->db->value(2.2E-54);
175
		$this->assertEquals('2.2E-54', (string)$result);
176
 
177
		setlocale(LC_NUMERIC, $restore);
178
	}
179
 
180
/**
181
 * test that scientific notations are working correctly
182
 *
183
 * @return void
184
 */
185
	public function testScientificNotation() {
186
		$result = $this->db->value(2.2E-54, 'float');
187
		$this->assertEquals('2.2E-54', (string)$result);
188
 
189
		$result = $this->db->value(2.2E-54);
190
		$this->assertEquals('2.2E-54', (string)$result);
191
	}
192
 
193
/**
194
 * testTinyintCasting method
195
 *
196
 *
197
 * @return void
198
 */
199
	public function testTinyintCasting() {
200
		$this->Dbo->cacheSources = false;
201
		$tableName = 'tinyint_' . uniqid();
202
		$this->Dbo->rawQuery('CREATE TABLE ' . $this->Dbo->fullTableName($tableName) . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id));');
203
 
204
		$this->model = new CakeTestModel(array(
205
			'name' => 'Tinyint', 'table' => $tableName, 'ds' => 'test'
206
		));
207
 
208
		$result = $this->model->schema();
209
		$this->assertEquals('boolean', $result['bool']['type']);
210
		$this->assertEquals('integer', $result['small_int']['type']);
211
 
212
		$this->assertTrue((bool)$this->model->save(array('bool' => 5, 'small_int' => 5)));
213
		$result = $this->model->find('first');
214
		$this->assertTrue($result['Tinyint']['bool']);
215
		$this->assertSame($result['Tinyint']['small_int'], '5');
216
		$this->model->deleteAll(true);
217
 
218
		$this->assertTrue((bool)$this->model->save(array('bool' => 0, 'small_int' => 100)));
219
		$result = $this->model->find('first');
220
		$this->assertFalse($result['Tinyint']['bool']);
221
		$this->assertSame($result['Tinyint']['small_int'], '100');
222
		$this->model->deleteAll(true);
223
 
224
		$this->assertTrue((bool)$this->model->save(array('bool' => true, 'small_int' => 0)));
225
		$result = $this->model->find('first');
226
		$this->assertTrue($result['Tinyint']['bool']);
227
		$this->assertSame($result['Tinyint']['small_int'], '0');
228
		$this->model->deleteAll(true);
229
 
230
		$this->Dbo->rawQuery('DROP TABLE ' . $this->Dbo->fullTableName($tableName));
231
	}
232
 
233
/**
234
 * testLastAffected method
235
 *
236
 *
237
 * @return void
238
 */
239
	public function testLastAffected() {
240
		$this->Dbo->cacheSources = false;
241
		$tableName = 'tinyint_' . uniqid();
242
		$this->Dbo->rawQuery('CREATE TABLE ' . $this->Dbo->fullTableName($tableName) . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id));');
243
 
244
		$this->model = new CakeTestModel(array(
245
			'name' => 'Tinyint', 'table' => $tableName, 'ds' => 'test'
246
		));
247
 
248
		$this->assertTrue((bool)$this->model->save(array('bool' => 5, 'small_int' => 5)));
249
		$this->assertEquals(1, $this->model->find('count'));
250
		$this->model->deleteAll(true);
251
		$result = $this->Dbo->lastAffected();
252
		$this->assertEquals(1, $result);
253
		$this->assertEquals(0, $this->model->find('count'));
254
 
255
		$this->Dbo->rawQuery('DROP TABLE ' . $this->Dbo->fullTableName($tableName));
256
	}
257
 
258
/**
259
 * testIndexDetection method
260
 *
261
 * @group indices
262
 * @return void
263
 */
264
	public function testIndexDetection() {
265
		$this->Dbo->cacheSources = false;
266
 
267
		$name = $this->Dbo->fullTableName('simple');
268
		$this->Dbo->rawQuery('CREATE TABLE ' . $name . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id));');
269
		$expected = array('PRIMARY' => array('column' => 'id', 'unique' => 1));
270
		$result = $this->Dbo->index('simple', false);
271
		$this->Dbo->rawQuery('DROP TABLE ' . $name);
272
		$this->assertEquals($expected, $result);
273
 
274
		$name = $this->Dbo->fullTableName('bigint');
275
		$this->Dbo->rawQuery('CREATE TABLE ' . $name . ' (id bigint(20) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id));');
276
		$expected = array('PRIMARY' => array('column' => 'id', 'unique' => 1));
277
		$result = $this->Dbo->index('bigint', false);
278
		$this->Dbo->rawQuery('DROP TABLE ' . $name);
279
		$this->assertEquals($expected, $result);
280
 
281
		$name = $this->Dbo->fullTableName('with_a_key');
282
		$this->Dbo->rawQuery('CREATE TABLE ' . $name . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id), KEY `pointless_bool` ( `bool` ));');
283
		$expected = array(
284
			'PRIMARY' => array('column' => 'id', 'unique' => 1),
285
			'pointless_bool' => array('column' => 'bool', 'unique' => 0),
286
		);
287
		$result = $this->Dbo->index('with_a_key', false);
288
		$this->Dbo->rawQuery('DROP TABLE ' . $name);
289
		$this->assertEquals($expected, $result);
290
 
291
		$name = $this->Dbo->fullTableName('with_two_keys');
292
		$this->Dbo->rawQuery('CREATE TABLE ' . $name . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id), KEY `pointless_bool` ( `bool` ), KEY `pointless_small_int` ( `small_int` ));');
293
		$expected = array(
294
			'PRIMARY' => array('column' => 'id', 'unique' => 1),
295
			'pointless_bool' => array('column' => 'bool', 'unique' => 0),
296
			'pointless_small_int' => array('column' => 'small_int', 'unique' => 0),
297
		);
298
		$result = $this->Dbo->index('with_two_keys', false);
299
		$this->Dbo->rawQuery('DROP TABLE ' . $name);
300
		$this->assertEquals($expected, $result);
301
 
302
		$name = $this->Dbo->fullTableName('with_compound_keys');
303
		$this->Dbo->rawQuery('CREATE TABLE ' . $name . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id), KEY `pointless_bool` ( `bool` ), KEY `pointless_small_int` ( `small_int` ), KEY `one_way` ( `bool`, `small_int` ));');
304
		$expected = array(
305
			'PRIMARY' => array('column' => 'id', 'unique' => 1),
306
			'pointless_bool' => array('column' => 'bool', 'unique' => 0),
307
			'pointless_small_int' => array('column' => 'small_int', 'unique' => 0),
308
			'one_way' => array('column' => array('bool', 'small_int'), 'unique' => 0),
309
		);
310
		$result = $this->Dbo->index('with_compound_keys', false);
311
		$this->Dbo->rawQuery('DROP TABLE ' . $name);
312
		$this->assertEquals($expected, $result);
313
 
314
		$name = $this->Dbo->fullTableName('with_multiple_compound_keys');
315
		$this->Dbo->rawQuery('CREATE TABLE ' . $name . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id), KEY `pointless_bool` ( `bool` ), KEY `pointless_small_int` ( `small_int` ), KEY `one_way` ( `bool`, `small_int` ), KEY `other_way` ( `small_int`, `bool` ));');
316
		$expected = array(
317
			'PRIMARY' => array('column' => 'id', 'unique' => 1),
318
			'pointless_bool' => array('column' => 'bool', 'unique' => 0),
319
			'pointless_small_int' => array('column' => 'small_int', 'unique' => 0),
320
			'one_way' => array('column' => array('bool', 'small_int'), 'unique' => 0),
321
			'other_way' => array('column' => array('small_int', 'bool'), 'unique' => 0),
322
		);
323
		$result = $this->Dbo->index('with_multiple_compound_keys', false);
324
		$this->Dbo->rawQuery('DROP TABLE ' . $name);
325
		$this->assertEquals($expected, $result);
326
 
327
		$name = $this->Dbo->fullTableName('with_fulltext');
328
		$this->Dbo->rawQuery('CREATE TABLE ' . $name . ' (id int(11) AUTO_INCREMENT, name varchar(255), description text, primary key(id), FULLTEXT KEY `MyFtIndex` ( `name`, `description` )) ENGINE=MyISAM;');
329
		$expected = array(
330
			'PRIMARY' => array('column' => 'id', 'unique' => 1),
331
			'MyFtIndex' => array('column' => array('name', 'description'), 'type' => 'fulltext')
332
		);
333
		$result = $this->Dbo->index('with_fulltext', false);
334
		$this->Dbo->rawQuery('DROP TABLE ' . $name);
335
		$this->assertEquals($expected, $result);
336
 
337
		$name = $this->Dbo->fullTableName('with_text_index');
338
		$this->Dbo->rawQuery('CREATE TABLE ' . $name . ' (id int(11) AUTO_INCREMENT, text_field text, primary key(id), KEY `text_index` ( `text_field`(20) ));');
339
		$expected = array(
340
			'PRIMARY' => array('column' => 'id', 'unique' => 1),
341
			'text_index' => array('column' => 'text_field', 'unique' => 0, 'length' => array('text_field' => 20)),
342
		);
343
		$result = $this->Dbo->index('with_text_index', false);
344
		$this->Dbo->rawQuery('DROP TABLE ' . $name);
345
		$this->assertEquals($expected, $result);
346
 
347
		$name = $this->Dbo->fullTableName('with_compound_text_index');
348
		$this->Dbo->rawQuery('CREATE TABLE ' . $name . ' (id int(11) AUTO_INCREMENT, text_field1 text, text_field2 text, primary key(id), KEY `text_index` ( `text_field1`(20), `text_field2`(20) ));');
349
		$expected = array(
350
			'PRIMARY' => array('column' => 'id', 'unique' => 1),
351
			'text_index' => array('column' => array('text_field1', 'text_field2'), 'unique' => 0, 'length' => array('text_field1' => 20, 'text_field2' => 20)),
352
		);
353
		$result = $this->Dbo->index('with_compound_text_index', false);
354
		$this->Dbo->rawQuery('DROP TABLE ' . $name);
355
		$this->assertEquals($expected, $result);
356
	}
357
 
358
/**
359
 * testBuildColumn method
360
 *
361
 * @return void
362
 */
363
	public function testBuildColumn() {
364
		$restore = $this->Dbo->columns;
365
		$this->Dbo->columns = array('varchar(255)' => 1);
366
		$data = array(
367
			'name' => 'testName',
368
			'type' => 'varchar(255)',
369
			'default',
370
			'null' => true,
371
			'key',
372
			'comment' => 'test'
373
		);
374
		$result = $this->Dbo->buildColumn($data);
375
		$expected = '`testName`  DEFAULT NULL COMMENT \'test\'';
376
		$this->assertEquals($expected, $result);
377
 
378
		$data = array(
379
			'name' => 'testName',
380
			'type' => 'varchar(255)',
381
			'default',
382
			'null' => true,
383
			'key',
384
			'charset' => 'utf8',
385
			'collate' => 'utf8_unicode_ci'
386
		);
387
		$result = $this->Dbo->buildColumn($data);
388
		$expected = '`testName`  CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL';
389
		$this->assertEquals($expected, $result);
390
		$this->Dbo->columns = $restore;
391
	}
392
 
393
/**
394
 * MySQL 4.x returns index data in a different format,
395
 * Using a mock ensure that MySQL 4.x output is properly parsed.
396
 *
397
 * @group indices
398
 * @return void
399
 */
400
	public function testIndexOnMySQL4Output() {
401
		$name = $this->Dbo->fullTableName('simple');
402
 
403
		$mockDbo = $this->getMock('Mysql', array('connect', '_execute', 'getVersion'));
404
		$columnData = array(
405
			array('0' => array(
406
				'Table' => 'with_compound_keys',
407
				'Non_unique' => '0',
408
				'Key_name' => 'PRIMARY',
409
				'Seq_in_index' => '1',
410
				'Column_name' => 'id',
411
				'Collation' => 'A',
412
				'Cardinality' => '0',
413
				'Sub_part' => null,
414
				'Packed' => null,
415
				'Null' => '',
416
				'Index_type' => 'BTREE',
417
				'Comment' => ''
418
			)),
419
			array('0' => array(
420
				'Table' => 'with_compound_keys',
421
				'Non_unique' => '1',
422
				'Key_name' => 'pointless_bool',
423
				'Seq_in_index' => '1',
424
				'Column_name' => 'bool',
425
				'Collation' => 'A',
426
				'Cardinality' => null,
427
				'Sub_part' => null,
428
				'Packed' => null,
429
				'Null' => 'YES',
430
				'Index_type' => 'BTREE',
431
				'Comment' => ''
432
			)),
433
			array('0' => array(
434
				'Table' => 'with_compound_keys',
435
				'Non_unique' => '1',
436
				'Key_name' => 'pointless_small_int',
437
				'Seq_in_index' => '1',
438
				'Column_name' => 'small_int',
439
				'Collation' => 'A',
440
				'Cardinality' => null,
441
				'Sub_part' => null,
442
				'Packed' => null,
443
				'Null' => 'YES',
444
				'Index_type' => 'BTREE',
445
				'Comment' => ''
446
			)),
447
			array('0' => array(
448
				'Table' => 'with_compound_keys',
449
				'Non_unique' => '1',
450
				'Key_name' => 'one_way',
451
				'Seq_in_index' => '1',
452
				'Column_name' => 'bool',
453
				'Collation' => 'A',
454
				'Cardinality' => null,
455
				'Sub_part' => null,
456
				'Packed' => null,
457
				'Null' => 'YES',
458
				'Index_type' => 'BTREE',
459
				'Comment' => ''
460
			)),
461
			array('0' => array(
462
				'Table' => 'with_compound_keys',
463
				'Non_unique' => '1',
464
				'Key_name' => 'one_way',
465
				'Seq_in_index' => '2',
466
				'Column_name' => 'small_int',
467
				'Collation' => 'A',
468
				'Cardinality' => null,
469
				'Sub_part' => null,
470
				'Packed' => null,
471
				'Null' => 'YES',
472
				'Index_type' => 'BTREE',
473
				'Comment' => ''
474
			))
475
		);
476
 
477
		$mockDbo->expects($this->once())->method('getVersion')->will($this->returnValue('4.1'));
478
		$resultMock = $this->getMock('PDOStatement', array('fetch'));
479
		$mockDbo->expects($this->once())
480
			->method('_execute')
481
			->with('SHOW INDEX FROM ' . $name)
482
			->will($this->returnValue($resultMock));
483
 
484
		foreach ($columnData as $i => $data) {
485
			$resultMock->expects($this->at($i))->method('fetch')->will($this->returnValue((object)$data));
486
		}
487
 
488
		$result = $mockDbo->index($name, false);
489
		$expected = array(
490
			'PRIMARY' => array('column' => 'id', 'unique' => 1),
491
			'pointless_bool' => array('column' => 'bool', 'unique' => 0),
492
			'pointless_small_int' => array('column' => 'small_int', 'unique' => 0),
493
			'one_way' => array('column' => array('bool', 'small_int'), 'unique' => 0),
494
		);
495
		$this->assertEquals($expected, $result);
496
	}
497
 
498
/**
499
 * testColumn method
500
 *
501
 * @return void
502
 */
503
	public function testColumn() {
504
		$result = $this->Dbo->column('varchar(50)');
505
		$expected = 'string';
506
		$this->assertEquals($expected, $result);
507
 
508
		$result = $this->Dbo->column('text');
509
		$expected = 'text';
510
		$this->assertEquals($expected, $result);
511
 
512
		$result = $this->Dbo->column('int(11)');
513
		$expected = 'integer';
514
		$this->assertEquals($expected, $result);
515
 
516
		$result = $this->Dbo->column('int(11) unsigned');
517
		$expected = 'integer';
518
		$this->assertEquals($expected, $result);
519
 
520
		$result = $this->Dbo->column('bigint(20)');
521
		$expected = 'biginteger';
522
		$this->assertEquals($expected, $result);
523
 
524
		$result = $this->Dbo->column('tinyint(1)');
525
		$expected = 'boolean';
526
		$this->assertEquals($expected, $result);
527
 
528
		$result = $this->Dbo->column('boolean');
529
		$expected = 'boolean';
530
		$this->assertEquals($expected, $result);
531
 
532
		$result = $this->Dbo->column('float');
533
		$expected = 'float';
534
		$this->assertEquals($expected, $result);
535
 
536
		$result = $this->Dbo->column('float unsigned');
537
		$expected = 'float';
538
		$this->assertEquals($expected, $result);
539
 
540
		$result = $this->Dbo->column('double unsigned');
541
		$expected = 'float';
542
		$this->assertEquals($expected, $result);
543
 
544
		$result = $this->Dbo->column('decimal(14,7) unsigned');
545
		$expected = 'float';
546
		$this->assertEquals($expected, $result);
547
	}
548
 
549
/**
550
 * testAlterSchemaIndexes method
551
 *
552
 * @group indices
553
 * @return void
554
 */
555
	public function testAlterSchemaIndexes() {
556
		$this->Dbo->cacheSources = $this->Dbo->testing = false;
557
		$table = $this->Dbo->fullTableName('altertest');
558
 
559
		$schemaA = new CakeSchema(array(
560
			'name' => 'AlterTest1',
561
			'connection' => 'test',
562
			'altertest' => array(
563
				'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
564
				'name' => array('type' => 'string', 'null' => false, 'length' => 50),
565
				'group1' => array('type' => 'integer', 'null' => true),
566
				'group2' => array('type' => 'integer', 'null' => true)
567
		)));
568
		$result = $this->Dbo->createSchema($schemaA);
569
		$this->assertContains('`id` int(11) DEFAULT 0 NOT NULL,', $result);
570
		$this->assertContains('`name` varchar(50) NOT NULL,', $result);
571
		$this->assertContains('`group1` int(11) DEFAULT NULL', $result);
572
		$this->assertContains('`group2` int(11) DEFAULT NULL', $result);
573
 
574
		//Test that the string is syntactically correct
575
		$query = $this->Dbo->getConnection()->prepare($result);
576
		$this->assertEquals($query->queryString, $result);
577
 
578
		$schemaB = new CakeSchema(array(
579
			'name' => 'AlterTest2',
580
			'connection' => 'test',
581
			'altertest' => array(
582
				'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
583
				'name' => array('type' => 'string', 'null' => false, 'length' => 50),
584
				'group1' => array('type' => 'integer', 'null' => true),
585
				'group2' => array('type' => 'integer', 'null' => true),
586
				'indexes' => array(
587
					'name_idx' => array('column' => 'name', 'unique' => 0),
588
					'group_idx' => array('column' => 'group1', 'unique' => 0),
589
					'compound_idx' => array('column' => array('group1', 'group2'), 'unique' => 0),
590
					'PRIMARY' => array('column' => 'id', 'unique' => 1))
591
		)));
592
 
593
		$result = $this->Dbo->alterSchema($schemaB->compare($schemaA));
594
		$this->assertContains("ALTER TABLE $table", $result);
595
		$this->assertContains('ADD KEY `name_idx` (`name`),', $result);
596
		$this->assertContains('ADD KEY `group_idx` (`group1`),', $result);
597
		$this->assertContains('ADD KEY `compound_idx` (`group1`, `group2`),', $result);
598
		$this->assertContains('ADD PRIMARY KEY  (`id`);', $result);
599
 
600
		//Test that the string is syntactically correct
601
		$query = $this->Dbo->getConnection()->prepare($result);
602
		$this->assertEquals($query->queryString, $result);
603
 
604
		// Change three indexes, delete one and add another one
605
		$schemaC = new CakeSchema(array(
606
			'name' => 'AlterTest3',
607
			'connection' => 'test',
608
			'altertest' => array(
609
				'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
610
				'name' => array('type' => 'string', 'null' => false, 'length' => 50),
611
				'group1' => array('type' => 'integer', 'null' => true),
612
				'group2' => array('type' => 'integer', 'null' => true),
613
				'indexes' => array(
614
					'name_idx' => array('column' => 'name', 'unique' => 1),
615
					'group_idx' => array('column' => 'group2', 'unique' => 0),
616
					'compound_idx' => array('column' => array('group2', 'group1'), 'unique' => 0),
617
					'id_name_idx' => array('column' => array('id', 'name'), 'unique' => 0))
618
		)));
619
 
620
		$result = $this->Dbo->alterSchema($schemaC->compare($schemaB));
621
		$this->assertContains("ALTER TABLE $table", $result);
622
		$this->assertContains('DROP PRIMARY KEY,', $result);
623
		$this->assertContains('DROP KEY `name_idx`,', $result);
624
		$this->assertContains('DROP KEY `group_idx`,', $result);
625
		$this->assertContains('DROP KEY `compound_idx`,', $result);
626
		$this->assertContains('ADD KEY `id_name_idx` (`id`, `name`),', $result);
627
		$this->assertContains('ADD UNIQUE KEY `name_idx` (`name`),', $result);
628
		$this->assertContains('ADD KEY `group_idx` (`group2`),', $result);
629
		$this->assertContains('ADD KEY `compound_idx` (`group2`, `group1`);', $result);
630
 
631
		$query = $this->Dbo->getConnection()->prepare($result);
632
		$this->assertEquals($query->queryString, $result);
633
 
634
		// Compare us to ourself.
635
		$this->assertEquals(array(), $schemaC->compare($schemaC));
636
 
637
		// Drop the indexes
638
		$result = $this->Dbo->alterSchema($schemaA->compare($schemaC));
639
 
640
		$this->assertContains("ALTER TABLE $table", $result);
641
		$this->assertContains('DROP KEY `name_idx`,', $result);
642
		$this->assertContains('DROP KEY `group_idx`,', $result);
643
		$this->assertContains('DROP KEY `compound_idx`,', $result);
644
		$this->assertContains('DROP KEY `id_name_idx`;', $result);
645
 
646
		$query = $this->Dbo->getConnection()->prepare($result);
647
		$this->assertEquals($query->queryString, $result);
648
	}
649
 
650
/**
651
 * test saving and retrieval of blobs
652
 *
653
 * @return void
654
 */
655
	public function testBlobSaving() {
656
		$this->loadFixtures('BinaryTest');
657
		$this->Dbo->cacheSources = false;
658
		$data = file_get_contents(CAKE . 'Test' . DS . 'test_app' . DS . 'webroot' . DS . 'img' . DS . 'cake.power.gif');
659
 
660
		$model = new CakeTestModel(array('name' => 'BinaryTest', 'ds' => 'test'));
661
		$model->save(compact('data'));
662
 
663
		$result = $model->find('first');
664
		$this->assertEquals($data, $result['BinaryTest']['data']);
665
	}
666
 
667
/**
668
 * test altering the table settings with schema.
669
 *
670
 * @return void
671
 */
672
	public function testAlteringTableParameters() {
673
		$this->Dbo->cacheSources = $this->Dbo->testing = false;
674
 
675
		$schemaA = new CakeSchema(array(
676
			'name' => 'AlterTest1',
677
			'connection' => 'test',
678
			'altertest' => array(
679
				'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
680
				'name' => array('type' => 'string', 'null' => false, 'length' => 50),
681
				'tableParameters' => array(
682
					'charset' => 'latin1',
683
					'collate' => 'latin1_general_ci',
684
					'engine' => 'MyISAM'
685
				)
686
			)
687
		));
688
		$this->Dbo->rawQuery($this->Dbo->createSchema($schemaA));
689
		$schemaB = new CakeSchema(array(
690
			'name' => 'AlterTest1',
691
			'connection' => 'test',
692
			'altertest' => array(
693
				'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
694
				'name' => array('type' => 'string', 'null' => false, 'length' => 50),
695
				'tableParameters' => array(
696
					'charset' => 'utf8',
697
					'collate' => 'utf8_general_ci',
698
					'engine' => 'InnoDB'
699
				)
700
			)
701
		));
702
		$result = $this->Dbo->alterSchema($schemaB->compare($schemaA));
703
		$this->assertContains('DEFAULT CHARSET=utf8', $result);
704
		$this->assertContains('ENGINE=InnoDB', $result);
705
		$this->assertContains('COLLATE=utf8_general_ci', $result);
706
 
707
		$this->Dbo->rawQuery($result);
708
		$result = $this->Dbo->listDetailedSources($this->Dbo->fullTableName('altertest', false, false));
709
		$this->assertEquals('utf8_general_ci', $result['Collation']);
710
		$this->assertEquals('InnoDB', $result['Engine']);
711
		$this->assertEquals('utf8', $result['charset']);
712
 
713
		$this->Dbo->rawQuery($this->Dbo->dropSchema($schemaA));
714
	}
715
 
716
/**
717
 * test alterSchema on two tables.
718
 *
719
 * @return void
720
 */
721
	public function testAlteringTwoTables() {
722
		$schema1 = new CakeSchema(array(
723
			'name' => 'AlterTest1',
724
			'connection' => 'test',
725
			'altertest' => array(
726
				'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
727
				'name' => array('type' => 'string', 'null' => false, 'length' => 50),
728
			),
729
			'other_table' => array(
730
				'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
731
				'name' => array('type' => 'string', 'null' => false, 'length' => 50),
732
			)
733
		));
734
		$schema2 = new CakeSchema(array(
735
			'name' => 'AlterTest1',
736
			'connection' => 'test',
737
			'altertest' => array(
738
				'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
739
				'field_two' => array('type' => 'string', 'null' => false, 'length' => 50),
740
			),
741
			'other_table' => array(
742
				'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
743
				'field_two' => array('type' => 'string', 'null' => false, 'length' => 50),
744
			)
745
		));
746
		$result = $this->Dbo->alterSchema($schema2->compare($schema1));
747
		$this->assertEquals(2, substr_count($result, 'field_two'), 'Too many fields');
748
	}
749
 
750
/**
751
 * testReadTableParameters method
752
 *
753
 * @return void
754
 */
755
	public function testReadTableParameters() {
756
		$this->Dbo->cacheSources = $this->Dbo->testing = false;
757
		$tableName = 'tinyint_' . uniqid();
758
		$table = $this->Dbo->fullTableName($tableName);
759
		$this->Dbo->rawQuery('CREATE TABLE ' . $table . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;');
760
		$result = $this->Dbo->readTableParameters($this->Dbo->fullTableName($tableName, false, false));
761
		$this->Dbo->rawQuery('DROP TABLE ' . $table);
762
		$expected = array(
763
			'charset' => 'utf8',
764
			'collate' => 'utf8_unicode_ci',
765
			'engine' => 'InnoDB');
766
		$this->assertEquals($expected, $result);
767
 
768
		$table = $this->Dbo->fullTableName($tableName);
769
		$this->Dbo->rawQuery('CREATE TABLE ' . $table . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id)) ENGINE=MyISAM DEFAULT CHARSET=cp1250 COLLATE=cp1250_general_ci;');
770
		$result = $this->Dbo->readTableParameters($this->Dbo->fullTableName($tableName, false, false));
771
		$this->Dbo->rawQuery('DROP TABLE ' . $table);
772
		$expected = array(
773
			'charset' => 'cp1250',
774
			'collate' => 'cp1250_general_ci',
775
			'engine' => 'MyISAM');
776
		$this->assertEquals($expected, $result);
777
	}
778
 
779
/**
780
 * testBuildTableParameters method
781
 *
782
 * @return void
783
 */
784
	public function testBuildTableParameters() {
785
		$this->Dbo->cacheSources = $this->Dbo->testing = false;
786
		$data = array(
787
			'charset' => 'utf8',
788
			'collate' => 'utf8_unicode_ci',
789
			'engine' => 'InnoDB');
790
		$result = $this->Dbo->buildTableParameters($data);
791
		$expected = array(
792
			'DEFAULT CHARSET=utf8',
793
			'COLLATE=utf8_unicode_ci',
794
			'ENGINE=InnoDB');
795
		$this->assertEquals($expected, $result);
796
	}
797
 
798
/**
799
 * testGetCharsetName method
800
 *
801
 * @return void
802
 */
803
	public function testGetCharsetName() {
804
		$this->Dbo->cacheSources = $this->Dbo->testing = false;
805
		$result = $this->Dbo->getCharsetName('utf8_unicode_ci');
806
		$this->assertEquals('utf8', $result);
807
		$result = $this->Dbo->getCharsetName('cp1250_general_ci');
808
		$this->assertEquals('cp1250', $result);
809
	}
810
 
811
/**
812
 * testGetCharsetNameCaching method
813
 *
814
 * @return void
815
 */
816
	public function testGetCharsetNameCaching() {
817
		$db = $this->getMock('Mysql', array('connect', '_execute', 'getVersion'));
818
		$queryResult = $this->getMock('PDOStatement');
819
 
820
		$db->expects($this->exactly(2))->method('getVersion')->will($this->returnValue('5.1'));
821
 
822
		$db->expects($this->exactly(1))
823
			->method('_execute')
824
			->with('SELECT CHARACTER_SET_NAME FROM INFORMATION_SCHEMA.COLLATIONS WHERE COLLATION_NAME = ?', array('utf8_unicode_ci'))
825
			->will($this->returnValue($queryResult));
826
 
827
		$queryResult->expects($this->once())
828
			->method('fetch')
829
			->with(PDO::FETCH_ASSOC)
830
			->will($this->returnValue(array('CHARACTER_SET_NAME' => 'utf8')));
831
 
832
		$result = $db->getCharsetName('utf8_unicode_ci');
833
		$this->assertEquals('utf8', $result);
834
 
835
		$result = $db->getCharsetName('utf8_unicode_ci');
836
		$this->assertEquals('utf8', $result);
837
	}
838
 
839
/**
840
 * test that changing the virtualFieldSeparator allows for __ fields.
841
 *
842
 * @return void
843
 */
844
	public function testVirtualFieldSeparators() {
845
		$this->loadFixtures('BinaryTest');
846
		$model = new CakeTestModel(array('table' => 'binary_tests', 'ds' => 'test', 'name' => 'BinaryTest'));
847
		$model->virtualFields = array(
848
			'other__field' => 'SUM(id)'
849
		);
850
 
851
		$this->Dbo->virtualFieldSeparator = '_$_';
852
		$result = $this->Dbo->fields($model, null, array('data', 'other__field'));
853
 
854
		$expected = array('`BinaryTest`.`data`', '(SUM(id)) AS  `BinaryTest_$_other__field`');
855
		$this->assertEquals($expected, $result);
856
	}
857
 
858
/**
859
 * Test describe() on a fixture.
860
 *
861
 * @return void
862
 */
863
	public function testDescribe() {
864
		$this->loadFixtures('Apple');
865
 
866
		$model = new Apple();
867
		$result = $this->Dbo->describe($model);
868
 
869
		$this->assertTrue(isset($result['id']));
870
		$this->assertTrue(isset($result['color']));
871
 
872
		$result = $this->Dbo->describe($model->useTable);
873
 
874
		$this->assertTrue(isset($result['id']));
875
		$this->assertTrue(isset($result['color']));
876
	}
877
 
878
/**
879
 * test that a describe() gets additional fieldParameters
880
 *
881
 * @return void
882
 */
883
	public function testDescribeGettingFieldParameters() {
884
		$schema = new CakeSchema(array(
885
			'connection' => 'test',
886
			'testdescribes' => array(
887
				'id' => array('type' => 'integer', 'key' => 'primary'),
888
				'stringy' => array(
889
					'type' => 'string',
890
					'null' => true,
891
					'charset' => 'cp1250',
892
					'collate' => 'cp1250_general_ci',
893
				),
894
				'other_col' => array(
895
					'type' => 'string',
896
					'null' => false,
897
					'charset' => 'latin1',
898
					'comment' => 'Test Comment'
899
				)
900
			)
901
		));
902
 
903
		$this->Dbo->execute($this->Dbo->createSchema($schema));
904
		$model = new CakeTestModel(array('table' => 'testdescribes', 'name' => 'Testdescribes'));
905
		$result = $model->getDataSource()->describe($model);
906
		$this->Dbo->execute($this->Dbo->dropSchema($schema));
907
 
908
		$this->assertEquals('cp1250_general_ci', $result['stringy']['collate']);
909
		$this->assertEquals('cp1250', $result['stringy']['charset']);
910
		$this->assertEquals('Test Comment', $result['other_col']['comment']);
911
	}
912
 
913
/**
914
 * Test that two columns with key => primary doesn't create invalid sql.
915
 *
916
 * @return void
917
 */
918
	public function testTwoColumnsWithPrimaryKey() {
919
		$schema = new CakeSchema(array(
920
			'connection' => 'test',
921
			'roles_users' => array(
922
				'role_id' => array(
923
					'type' => 'integer',
924
					'null' => false,
925
					'default' => null,
926
					'key' => 'primary'
927
				),
928
				'user_id' => array(
929
					'type' => 'integer',
930
					'null' => false,
931
					'default' => null,
932
					'key' => 'primary'
933
				),
934
				'indexes' => array(
935
					'user_role_index' => array(
936
						'column' => array('role_id', 'user_id'),
937
						'unique' => 1
938
					),
939
					'user_index' => array(
940
						'column' => 'user_id',
941
						'unique' => 0
942
					)
943
				),
944
			)
945
		));
946
 
947
		$result = $this->Dbo->createSchema($schema);
948
		$this->assertContains('`role_id` int(11) NOT NULL,', $result);
949
		$this->assertContains('`user_id` int(11) NOT NULL,', $result);
950
	}
951
 
952
/**
953
 * Test that the primary flag is handled correctly.
954
 *
955
 * @return void
956
 */
957
	public function testCreateSchemaAutoPrimaryKey() {
958
		$schema = new CakeSchema();
959
		$schema->tables = array(
960
			'no_indexes' => array(
961
				'id' => array('type' => 'integer', 'null' => false, 'key' => 'primary'),
962
				'data' => array('type' => 'integer', 'null' => false),
963
				'indexes' => array(),
964
			)
965
		);
966
		$result = $this->Dbo->createSchema($schema, 'no_indexes');
967
		$this->assertContains('PRIMARY KEY  (`id`)', $result);
968
		$this->assertNotContains('UNIQUE KEY', $result);
969
 
970
		$schema->tables = array(
971
			'primary_index' => array(
972
				'id' => array('type' => 'integer', 'null' => false),
973
				'data' => array('type' => 'integer', 'null' => false),
974
				'indexes' => array(
975
					'PRIMARY' => array('column' => 'id', 'unique' => 1),
976
					'some_index' => array('column' => 'data', 'unique' => 1)
977
				),
978
			)
979
		);
980
		$result = $this->Dbo->createSchema($schema, 'primary_index');
981
		$this->assertContains('PRIMARY KEY  (`id`)', $result);
982
		$this->assertContains('UNIQUE KEY `some_index` (`data`)', $result);
983
 
984
		$schema->tables = array(
985
			'primary_flag_has_index' => array(
986
				'id' => array('type' => 'integer', 'null' => false, 'key' => 'primary'),
987
				'data' => array('type' => 'integer', 'null' => false),
988
				'indexes' => array(
989
					'some_index' => array('column' => 'data', 'unique' => 1)
990
				),
991
			)
992
		);
993
		$result = $this->Dbo->createSchema($schema, 'primary_flag_has_index');
994
		$this->assertContains('PRIMARY KEY  (`id`)', $result);
995
		$this->assertContains('UNIQUE KEY `some_index` (`data`)', $result);
996
	}
997
 
998
/**
999
 * Tests that listSources method sends the correct query and parses the result accordingly
1000
 * @return void
1001
 */
1002
	public function testListSources() {
1003
		$db = $this->getMock('Mysql', array('connect', '_execute'));
1004
		$queryResult = $this->getMock('PDOStatement');
1005
		$db->expects($this->once())
1006
			->method('_execute')
1007
			->with('SHOW TABLES FROM `cake`')
1008
			->will($this->returnValue($queryResult));
1009
		$queryResult->expects($this->at(0))
1010
			->method('fetch')
1011
			->will($this->returnValue(array('cake_table')));
1012
		$queryResult->expects($this->at(1))
1013
			->method('fetch')
1014
			->will($this->returnValue(array('another_table')));
1015
		$queryResult->expects($this->at(2))
1016
			->method('fetch')
1017
			->will($this->returnValue(null));
1018
 
1019
		$tables = $db->listSources();
1020
		$this->assertEquals(array('cake_table', 'another_table'), $tables);
1021
	}
1022
 
1023
/**
1024
 * test that listDetailedSources with a named table that doesn't exist.
1025
 *
1026
 * @return void
1027
 */
1028
	public function testListDetailedSourcesNamed() {
1029
		$this->loadFixtures('Apple');
1030
 
1031
		$result = $this->Dbo->listDetailedSources('imaginary');
1032
		$this->assertEquals(array(), $result, 'Should be empty when table does not exist.');
1033
 
1034
		$result = $this->Dbo->listDetailedSources();
1035
		$tableName = $this->Dbo->fullTableName('apples', false, false);
1036
		$this->assertTrue(isset($result[$tableName]), 'Key should exist');
1037
	}
1038
 
1039
/**
1040
 * Tests that getVersion method sends the correct query for getting the mysql version
1041
 * @return void
1042
 */
1043
	public function testGetVersion() {
1044
		$version = $this->Dbo->getVersion();
1045
		$this->assertTrue(is_string($version));
1046
	}
1047
 
1048
/**
1049
 * Tests that getVersion method sends the correct query for getting the client encoding
1050
 * @return void
1051
 */
1052
	public function testGetEncoding() {
1053
		$db = $this->getMock('Mysql', array('connect', '_execute'));
1054
		$queryResult = $this->getMock('PDOStatement');
1055
 
1056
		$db->expects($this->once())
1057
			->method('_execute')
1058
			->with('SHOW VARIABLES LIKE ?', array('character_set_client'))
1059
			->will($this->returnValue($queryResult));
1060
		$result = new StdClass;
1061
		$result->Value = 'utf-8';
1062
		$queryResult->expects($this->once())
1063
			->method('fetchObject')
1064
			->will($this->returnValue($result));
1065
 
1066
		$encoding = $db->getEncoding();
1067
		$this->assertEquals('utf-8', $encoding);
1068
	}
1069
 
1070
/**
1071
 * testFieldDoubleEscaping method
1072
 *
1073
 * @return void
1074
 */
1075
	public function testFieldDoubleEscaping() {
1076
		$db = $this->Dbo->config['database'];
1077
		$test = $this->getMock('Mysql', array('connect', '_execute', 'execute'));
1078
		$test->config['database'] = $db;
1079
 
1080
		$this->Model = $this->getMock('Article2', array('getDataSource'));
1081
		$this->Model->alias = 'Article';
1082
		$this->Model->expects($this->any())
1083
			->method('getDataSource')
1084
			->will($this->returnValue($test));
1085
 
1086
		$this->assertEquals('`Article`.`id`', $this->Model->escapeField());
1087
		$result = $test->fields($this->Model, null, $this->Model->escapeField());
1088
		$this->assertEquals(array('`Article`.`id`'), $result);
1089
 
1090
		$test->expects($this->at(0))->method('execute')
1091
			->with('SELECT `Article`.`id` FROM ' . $test->fullTableName('articles') . ' AS `Article`   WHERE 1 = 1');
1092
 
1093
		$result = $test->read($this->Model, array(
1094
			'fields' => $this->Model->escapeField(),
1095
			'conditions' => null,
1096
			'recursive' => -1
1097
		));
1098
 
1099
		$test->startQuote = '[';
1100
		$test->endQuote = ']';
1101
		$this->assertEquals('[Article].[id]', $this->Model->escapeField());
1102
 
1103
		$result = $test->fields($this->Model, null, $this->Model->escapeField());
1104
		$this->assertEquals(array('[Article].[id]'), $result);
1105
 
1106
		$test->expects($this->at(0))->method('execute')
1107
			->with('SELECT [Article].[id] FROM ' . $test->fullTableName('articles') . ' AS [Article]   WHERE 1 = 1');
1108
		$result = $test->read($this->Model, array(
1109
			'fields' => $this->Model->escapeField(),
1110
			'conditions' => null,
1111
			'recursive' => -1
1112
		));
1113
	}
1114
 
1115
/**
1116
 * testGenerateAssociationQuerySelfJoin method
1117
 *
1118
 * @return void
1119
 */
1120
	public function testGenerateAssociationQuerySelfJoin() {
1121
		$this->Dbo = $this->getMock('Mysql', array('connect', '_execute', 'execute'));
1122
		$this->startTime = microtime(true);
1123
		$this->Model = new Article2();
1124
		$this->_buildRelatedModels($this->Model);
1125
		$this->_buildRelatedModels($this->Model->Category2);
1126
		$this->Model->Category2->ChildCat = new Category2();
1127
		$this->Model->Category2->ParentCat = new Category2();
1128
 
1129
		$queryData = array();
1130
 
1131
		foreach ($this->Model->Category2->associations() as $type) {
1132
			foreach ($this->Model->Category2->{$type} as $assoc => $assocData) {
1133
				$linkModel = $this->Model->Category2->{$assoc};
1134
				$external = isset($assocData['external']);
1135
 
1136
				if ($this->Model->Category2->alias == $linkModel->alias && $type !== 'hasAndBelongsToMany' && $type !== 'hasMany') {
1137
					$result = $this->Dbo->generateAssociationQuery($this->Model->Category2, $linkModel, $type, $assoc, $assocData, $queryData, $external, $null);
1138
					$this->assertFalse(empty($result));
1139
				} else {
1140
					if ($this->Model->Category2->useDbConfig == $linkModel->useDbConfig) {
1141
						$result = $this->Dbo->generateAssociationQuery($this->Model->Category2, $linkModel, $type, $assoc, $assocData, $queryData, $external, $null);
1142
						$this->assertFalse(empty($result));
1143
					}
1144
				}
1145
			}
1146
		}
1147
 
1148
		$query = $this->Dbo->generateAssociationQuery($this->Model->Category2, $null, null, null, null, $queryData, false, $null);
1149
		$this->assertRegExp('/^SELECT\s+(.+)FROM(.+)`Category2`\.`group_id`\s+=\s+`Group`\.`id`\)\s+LEFT JOIN(.+)WHERE\s+1 = 1\s*$/', $query);
1150
 
1151
		$this->Model = new TestModel4();
1152
		$this->Model->schema();
1153
		$this->_buildRelatedModels($this->Model);
1154
 
1155
		$binding = array('type' => 'belongsTo', 'model' => 'TestModel4Parent');
1156
		$queryData = array();
1157
		$resultSet = null;
1158
		$null = null;
1159
 
1160
		$params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
1161
 
1162
		$_queryData = $queryData;
1163
		$result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
1164
		$this->assertTrue($result);
1165
 
1166
		$expected = array(
1167
			'conditions' => array(),
1168
			'fields' => array(
1169
				'`TestModel4`.`id`',
1170
				'`TestModel4`.`name`',
1171
				'`TestModel4`.`created`',
1172
				'`TestModel4`.`updated`',
1173
				'`TestModel4Parent`.`id`',
1174
				'`TestModel4Parent`.`name`',
1175
				'`TestModel4Parent`.`created`',
1176
				'`TestModel4Parent`.`updated`'
1177
			),
1178
			'joins' => array(
1179
				array(
1180
					'table' => $this->Dbo->fullTableName($this->Model),
1181
					'alias' => 'TestModel4Parent',
1182
					'type' => 'LEFT',
1183
					'conditions' => '`TestModel4`.`parent_id` = `TestModel4Parent`.`id`'
1184
				)
1185
			),
1186
			'order' => array(),
1187
			'limit' => array(),
1188
			'offset' => array(),
1189
			'group' => array(),
1190
			'callbacks' => null
1191
		);
1192
		$queryData['joins'][0]['table'] = $this->Dbo->fullTableName($queryData['joins'][0]['table']);
1193
		$this->assertEquals($expected, $queryData);
1194
 
1195
		$result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
1196
		$this->assertRegExp('/^SELECT\s+`TestModel4`\.`id`, `TestModel4`\.`name`, `TestModel4`\.`created`, `TestModel4`\.`updated`, `TestModel4Parent`\.`id`, `TestModel4Parent`\.`name`, `TestModel4Parent`\.`created`, `TestModel4Parent`\.`updated`\s+/', $result);
1197
		$this->assertRegExp('/FROM\s+\S+`test_model4` AS `TestModel4`\s+LEFT JOIN\s+\S+`test_model4` AS `TestModel4Parent`/', $result);
1198
		$this->assertRegExp('/\s+ON\s+\(`TestModel4`.`parent_id` = `TestModel4Parent`.`id`\)\s+WHERE/', $result);
1199
		$this->assertRegExp('/\s+WHERE\s+1 = 1$/', $result);
1200
 
1201
		$params['assocData']['type'] = 'INNER';
1202
		$this->Model->belongsTo['TestModel4Parent']['type'] = 'INNER';
1203
		$result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $_queryData, $params['external'], $resultSet);
1204
		$this->assertTrue($result);
1205
		$this->assertEquals('INNER', $_queryData['joins'][0]['type']);
1206
	}
1207
 
1208
/**
1209
 * buildRelatedModels method
1210
 *
1211
 * @param Model $model
1212
 * @return void
1213
 */
1214
	protected function _buildRelatedModels(Model $model) {
1215
		foreach ($model->associations() as $type) {
1216
			foreach ($model->{$type} as $assocData) {
1217
				if (is_string($assocData)) {
1218
					$className = $assocData;
1219
				} elseif (isset($assocData['className'])) {
1220
					$className = $assocData['className'];
1221
				}
1222
				$model->$className = new $className();
1223
				$model->$className->schema();
1224
			}
1225
		}
1226
	}
1227
 
1228
/**
1229
 * &_prepareAssociationQuery method
1230
 *
1231
 * @param Model $model
1232
 * @param array $queryData
1233
 * @param array $binding
1234
 * @return void
1235
 */
1236
	protected function &_prepareAssociationQuery(Model $model, &$queryData, $binding) {
1237
		$type = $binding['type'];
1238
		$assoc = $binding['model'];
1239
		$assocData = $model->{$type}[$assoc];
1240
		$className = $assocData['className'];
1241
 
1242
		$linkModel = $model->{$className};
1243
		$external = isset($assocData['external']);
1244
		$queryData = $this->_scrubQueryData($queryData);
1245
 
1246
		$result = array_merge(array('linkModel' => &$linkModel), compact('type', 'assoc', 'assocData', 'external'));
1247
		return $result;
1248
	}
1249
 
1250
/**
1251
 * Helper method copied from DboSource::_scrubQueryData()
1252
 *
1253
 * @param array $data
1254
 * @return array
1255
 */
1256
	protected function _scrubQueryData($data) {
1257
		static $base = null;
1258
		if ($base === null) {
1259
			$base = array_fill_keys(array('conditions', 'fields', 'joins', 'order', 'limit', 'offset', 'group'), array());
1260
			$base['callbacks'] = null;
1261
		}
1262
		return (array)$data + $base;
1263
	}
1264
 
1265
/**
1266
 * testGenerateInnerJoinAssociationQuery method
1267
 *
1268
 * @return void
1269
 */
1270
	public function testGenerateInnerJoinAssociationQuery() {
1271
		$db = $this->Dbo->config['database'];
1272
		$test = $this->getMock('Mysql', array('connect', '_execute', 'execute'));
1273
		$test->config['database'] = $db;
1274
 
1275
		$this->Model = $this->getMock('TestModel9', array('getDataSource'));
1276
		$this->Model->expects($this->any())
1277
			->method('getDataSource')
1278
			->will($this->returnValue($test));
1279
 
1280
		$this->Model->TestModel8 = $this->getMock('TestModel8', array('getDataSource'));
1281
		$this->Model->TestModel8->expects($this->any())
1282
			->method('getDataSource')
1283
			->will($this->returnValue($test));
1284
 
1285
		$testModel8Table = $this->Model->TestModel8->getDataSource()->fullTableName($this->Model->TestModel8);
1286
 
1287
		$test->expects($this->at(0))->method('execute')
1288
			->with($this->stringContains('`TestModel9` LEFT JOIN ' . $testModel8Table));
1289
 
1290
		$test->expects($this->at(1))->method('execute')
1291
			->with($this->stringContains('TestModel9` INNER JOIN ' . $testModel8Table));
1292
 
1293
		$test->read($this->Model, array('recursive' => 1));
1294
		$this->Model->belongsTo['TestModel8']['type'] = 'INNER';
1295
		$test->read($this->Model, array('recursive' => 1));
1296
	}
1297
 
1298
/**
1299
 * testGenerateAssociationQuerySelfJoinWithConditionsInHasOneBinding method
1300
 *
1301
 * @return void
1302
 */
1303
	public function testGenerateAssociationQuerySelfJoinWithConditionsInHasOneBinding() {
1304
		$this->Model = new TestModel8();
1305
		$this->Model->schema();
1306
		$this->_buildRelatedModels($this->Model);
1307
 
1308
		$binding = array('type' => 'hasOne', 'model' => 'TestModel9');
1309
		$queryData = array();
1310
		$resultSet = null;
1311
		$null = null;
1312
 
1313
		$params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
1314
		$result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
1315
		$this->assertTrue($result);
1316
 
1317
		$result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
1318
		$this->assertRegExp('/^SELECT\s+`TestModel8`\.`id`, `TestModel8`\.`test_model9_id`, `TestModel8`\.`name`, `TestModel8`\.`created`, `TestModel8`\.`updated`, `TestModel9`\.`id`, `TestModel9`\.`test_model8_id`, `TestModel9`\.`name`, `TestModel9`\.`created`, `TestModel9`\.`updated`\s+/', $result);
1319
		$this->assertRegExp('/FROM\s+\S+`test_model8` AS `TestModel8`\s+LEFT JOIN\s+\S+`test_model9` AS `TestModel9`/', $result);
1320
		$this->assertRegExp('/\s+ON\s+\(`TestModel9`\.`name` != \'mariano\'\s+AND\s+`TestModel9`.`test_model8_id` = `TestModel8`.`id`\)\s+WHERE/', $result);
1321
		$this->assertRegExp('/\s+WHERE\s+(?:\()?1\s+=\s+1(?:\))?\s*$/', $result);
1322
	}
1323
 
1324
/**
1325
 * testGenerateAssociationQuerySelfJoinWithConditionsInBelongsToBinding method
1326
 *
1327
 * @return void
1328
 */
1329
	public function testGenerateAssociationQuerySelfJoinWithConditionsInBelongsToBinding() {
1330
		$this->Model = new TestModel9();
1331
		$this->Model->schema();
1332
		$this->_buildRelatedModels($this->Model);
1333
 
1334
		$binding = array('type' => 'belongsTo', 'model' => 'TestModel8');
1335
		$queryData = array();
1336
		$resultSet = null;
1337
		$null = null;
1338
 
1339
		$params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
1340
		$result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
1341
		$this->assertTrue($result);
1342
 
1343
		$result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
1344
		$this->assertRegExp('/^SELECT\s+`TestModel9`\.`id`, `TestModel9`\.`test_model8_id`, `TestModel9`\.`name`, `TestModel9`\.`created`, `TestModel9`\.`updated`, `TestModel8`\.`id`, `TestModel8`\.`test_model9_id`, `TestModel8`\.`name`, `TestModel8`\.`created`, `TestModel8`\.`updated`\s+/', $result);
1345
		$this->assertRegExp('/FROM\s+\S+`test_model9` AS `TestModel9`\s+LEFT JOIN\s+\S+`test_model8` AS `TestModel8`/', $result);
1346
		$this->assertRegExp('/\s+ON\s+\(`TestModel8`\.`name` != \'larry\'\s+AND\s+`TestModel9`.`test_model8_id` = `TestModel8`.`id`\)\s+WHERE/', $result);
1347
		$this->assertRegExp('/\s+WHERE\s+(?:\()?1\s+=\s+1(?:\))?\s*$/', $result);
1348
	}
1349
 
1350
/**
1351
 * testGenerateAssociationQuerySelfJoinWithConditions method
1352
 *
1353
 * @return void
1354
 */
1355
	public function testGenerateAssociationQuerySelfJoinWithConditions() {
1356
		$this->Model = new TestModel4();
1357
		$this->Model->schema();
1358
		$this->_buildRelatedModels($this->Model);
1359
 
1360
		$binding = array('type' => 'belongsTo', 'model' => 'TestModel4Parent');
1361
		$queryData = array('conditions' => array('TestModel4Parent.name !=' => 'mariano'));
1362
		$resultSet = null;
1363
		$null = null;
1364
 
1365
		$params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
1366
 
1367
		$result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
1368
		$this->assertTrue($result);
1369
 
1370
		$result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
1371
		$this->assertRegExp('/^SELECT\s+`TestModel4`\.`id`, `TestModel4`\.`name`, `TestModel4`\.`created`, `TestModel4`\.`updated`, `TestModel4Parent`\.`id`, `TestModel4Parent`\.`name`, `TestModel4Parent`\.`created`, `TestModel4Parent`\.`updated`\s+/', $result);
1372
		$this->assertRegExp('/FROM\s+\S+`test_model4` AS `TestModel4`\s+LEFT JOIN\s+\S+`test_model4` AS `TestModel4Parent`/', $result);
1373
		$this->assertRegExp('/\s+ON\s+\(`TestModel4`.`parent_id` = `TestModel4Parent`.`id`\)\s+WHERE/', $result);
1374
		$this->assertRegExp('/\s+WHERE\s+(?:\()?`TestModel4Parent`.`name`\s+!=\s+\'mariano\'(?:\))?\s*$/', $result);
1375
 
1376
		$this->Featured2 = new Featured2();
1377
		$this->Featured2->schema();
1378
 
1379
		$this->Featured2->bindModel(array(
1380
			'belongsTo' => array(
1381
				'ArticleFeatured2' => array(
1382
					'conditions' => 'ArticleFeatured2.published = \'Y\'',
1383
					'fields' => 'id, title, user_id, published'
1384
				)
1385
			)
1386
		));
1387
 
1388
		$this->_buildRelatedModels($this->Featured2);
1389
 
1390
		$binding = array('type' => 'belongsTo', 'model' => 'ArticleFeatured2');
1391
		$queryData = array('conditions' => array());
1392
		$resultSet = null;
1393
		$null = null;
1394
 
1395
		$params = &$this->_prepareAssociationQuery($this->Featured2, $queryData, $binding);
1396
 
1397
		$result = $this->Dbo->generateAssociationQuery($this->Featured2, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
1398
		$this->assertTrue($result);
1399
		$result = $this->Dbo->generateAssociationQuery($this->Featured2, $null, null, null, null, $queryData, false, $null);
1400
 
1401
		$this->assertRegExp(
1402
			'/^SELECT\s+`Featured2`\.`id`, `Featured2`\.`article_id`, `Featured2`\.`category_id`, `Featured2`\.`name`,\s+' .
1403
			'`ArticleFeatured2`\.`id`, `ArticleFeatured2`\.`title`, `ArticleFeatured2`\.`user_id`, `ArticleFeatured2`\.`published`\s+' .
1404
			'FROM\s+\S+`featured2` AS `Featured2`\s+LEFT JOIN\s+\S+`article_featured` AS `ArticleFeatured2`' .
1405
			'\s+ON\s+\(`ArticleFeatured2`.`published` = \'Y\'\s+AND\s+`Featured2`\.`article_featured2_id` = `ArticleFeatured2`\.`id`\)' .
1406
			'\s+WHERE\s+1\s+=\s+1\s*$/',
1407
			$result
1408
		);
1409
	}
1410
 
1411
/**
1412
 * testGenerateAssociationQueryHasOne method
1413
 *
1414
 * @return void
1415
 */
1416
	public function testGenerateAssociationQueryHasOne() {
1417
		$this->Model = new TestModel4();
1418
		$this->Model->schema();
1419
		$this->_buildRelatedModels($this->Model);
1420
 
1421
		$binding = array('type' => 'hasOne', 'model' => 'TestModel5');
1422
 
1423
		$queryData = array();
1424
		$resultSet = null;
1425
		$null = null;
1426
 
1427
		$params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
1428
 
1429
		$result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
1430
		$this->assertTrue($result);
1431
 
1432
		$testModel5Table = $this->Dbo->fullTableName($this->Model->TestModel5);
1433
		$result = $this->Dbo->buildJoinStatement($queryData['joins'][0]);
1434
		$expected = ' LEFT JOIN ' . $testModel5Table . ' AS `TestModel5` ON (`TestModel5`.`test_model4_id` = `TestModel4`.`id`)';
1435
		$this->assertEquals(trim($expected), trim($result));
1436
 
1437
		$result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
1438
		$this->assertRegExp('/^SELECT\s+`TestModel4`\.`id`, `TestModel4`\.`name`, `TestModel4`\.`created`, `TestModel4`\.`updated`, `TestModel5`\.`id`, `TestModel5`\.`test_model4_id`, `TestModel5`\.`name`, `TestModel5`\.`created`, `TestModel5`\.`updated`\s+/', $result);
1439
		$this->assertRegExp('/\s+FROM\s+\S+`test_model4` AS `TestModel4`\s+LEFT JOIN\s+/', $result);
1440
		$this->assertRegExp('/`test_model5` AS `TestModel5`\s+ON\s+\(`TestModel5`.`test_model4_id` = `TestModel4`.`id`\)\s+WHERE/', $result);
1441
		$this->assertRegExp('/\s+WHERE\s+(?:\()?\s*1 = 1\s*(?:\))?\s*$/', $result);
1442
	}
1443
 
1444
/**
1445
 * testGenerateAssociationQueryHasOneWithConditions method
1446
 *
1447
 * @return void
1448
 */
1449
	public function testGenerateAssociationQueryHasOneWithConditions() {
1450
		$this->Model = new TestModel4();
1451
		$this->Model->schema();
1452
		$this->_buildRelatedModels($this->Model);
1453
 
1454
		$binding = array('type' => 'hasOne', 'model' => 'TestModel5');
1455
 
1456
		$queryData = array('conditions' => array('TestModel5.name !=' => 'mariano'));
1457
		$resultSet = null;
1458
		$null = null;
1459
 
1460
		$params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
1461
 
1462
		$result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
1463
		$this->assertTrue($result);
1464
 
1465
		$result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
1466
 
1467
		$this->assertRegExp('/^SELECT\s+`TestModel4`\.`id`, `TestModel4`\.`name`, `TestModel4`\.`created`, `TestModel4`\.`updated`, `TestModel5`\.`id`, `TestModel5`\.`test_model4_id`, `TestModel5`\.`name`, `TestModel5`\.`created`, `TestModel5`\.`updated`\s+/', $result);
1468
		$this->assertRegExp('/\s+FROM\s+\S+`test_model4` AS `TestModel4`\s+LEFT JOIN\s+\S+`test_model5` AS `TestModel5`/', $result);
1469
		$this->assertRegExp('/\s+ON\s+\(`TestModel5`.`test_model4_id`\s+=\s+`TestModel4`.`id`\)\s+WHERE/', $result);
1470
		$this->assertRegExp('/\s+WHERE\s+(?:\()?\s*`TestModel5`.`name`\s+!=\s+\'mariano\'\s*(?:\))?\s*$/', $result);
1471
	}
1472
 
1473
/**
1474
 * testGenerateAssociationQueryBelongsTo method
1475
 *
1476
 * @return void
1477
 */
1478
	public function testGenerateAssociationQueryBelongsTo() {
1479
		$this->Model = new TestModel5();
1480
		$this->Model->schema();
1481
		$this->_buildRelatedModels($this->Model);
1482
 
1483
		$binding = array('type' => 'belongsTo', 'model' => 'TestModel4');
1484
		$queryData = array();
1485
		$resultSet = null;
1486
		$null = null;
1487
 
1488
		$params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
1489
 
1490
		$result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
1491
		$this->assertTrue($result);
1492
 
1493
		$testModel4Table = $this->Dbo->fullTableName($this->Model->TestModel4, true, true);
1494
		$result = $this->Dbo->buildJoinStatement($queryData['joins'][0]);
1495
		$expected = ' LEFT JOIN ' . $testModel4Table . ' AS `TestModel4` ON (`TestModel5`.`test_model4_id` = `TestModel4`.`id`)';
1496
		$this->assertEquals(trim($expected), trim($result));
1497
 
1498
		$result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
1499
		$this->assertRegExp('/^SELECT\s+`TestModel5`\.`id`, `TestModel5`\.`test_model4_id`, `TestModel5`\.`name`, `TestModel5`\.`created`, `TestModel5`\.`updated`, `TestModel4`\.`id`, `TestModel4`\.`name`, `TestModel4`\.`created`, `TestModel4`\.`updated`\s+/', $result);
1500
		$this->assertRegExp('/\s+FROM\s+\S+`test_model5` AS `TestModel5`\s+LEFT JOIN\s+\S+`test_model4` AS `TestModel4`/', $result);
1501
		$this->assertRegExp('/\s+ON\s+\(`TestModel5`.`test_model4_id` = `TestModel4`.`id`\)\s+WHERE\s+/', $result);
1502
		$this->assertRegExp('/\s+WHERE\s+(?:\()?\s*1 = 1\s*(?:\))?\s*$/', $result);
1503
	}
1504
 
1505
/**
1506
 * testGenerateAssociationQueryBelongsToWithConditions method
1507
 *
1508
 * @return void
1509
 */
1510
	public function testGenerateAssociationQueryBelongsToWithConditions() {
1511
		$this->Model = new TestModel5();
1512
		$this->Model->schema();
1513
		$this->_buildRelatedModels($this->Model);
1514
 
1515
		$binding = array('type' => 'belongsTo', 'model' => 'TestModel4');
1516
		$queryData = array('conditions' => array('TestModel5.name !=' => 'mariano'));
1517
		$resultSet = null;
1518
		$null = null;
1519
 
1520
		$params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
1521
 
1522
		$result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
1523
		$this->assertTrue($result);
1524
 
1525
		$testModel4Table = $this->Dbo->fullTableName($this->Model->TestModel4, true, true);
1526
		$result = $this->Dbo->buildJoinStatement($queryData['joins'][0]);
1527
		$expected = ' LEFT JOIN ' . $testModel4Table . ' AS `TestModel4` ON (`TestModel5`.`test_model4_id` = `TestModel4`.`id`)';
1528
		$this->assertEquals(trim($expected), trim($result));
1529
 
1530
		$result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
1531
		$this->assertRegExp('/^SELECT\s+`TestModel5`\.`id`, `TestModel5`\.`test_model4_id`, `TestModel5`\.`name`, `TestModel5`\.`created`, `TestModel5`\.`updated`, `TestModel4`\.`id`, `TestModel4`\.`name`, `TestModel4`\.`created`, `TestModel4`\.`updated`\s+/', $result);
1532
		$this->assertRegExp('/\s+FROM\s+\S+`test_model5` AS `TestModel5`\s+LEFT JOIN\s+\S+`test_model4` AS `TestModel4`/', $result);
1533
		$this->assertRegExp('/\s+ON\s+\(`TestModel5`.`test_model4_id` = `TestModel4`.`id`\)\s+WHERE\s+/', $result);
1534
		$this->assertRegExp('/\s+WHERE\s+`TestModel5`.`name` != \'mariano\'\s*$/', $result);
1535
	}
1536
 
1537
/**
1538
 * testGenerateAssociationQueryHasMany method
1539
 *
1540
 * @return void
1541
 */
1542
	public function testGenerateAssociationQueryHasMany() {
1543
		$this->Model = new TestModel5();
1544
		$this->Model->schema();
1545
		$this->_buildRelatedModels($this->Model);
1546
 
1547
		$binding = array('type' => 'hasMany', 'model' => 'TestModel6');
1548
		$queryData = array();
1549
		$resultSet = null;
1550
		$null = null;
1551
 
1552
		$params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
1553
 
1554
		$result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
1555
 
1556
		$this->assertRegExp('/^SELECT\s+`TestModel6`\.`id`, `TestModel6`\.`test_model5_id`, `TestModel6`\.`name`, `TestModel6`\.`created`, `TestModel6`\.`updated`\s+/', $result);
1557
		$this->assertRegExp('/\s+FROM\s+\S+`test_model6` AS `TestModel6`\s+WHERE/', $result);
1558
		$this->assertRegExp('/\s+WHERE\s+`TestModel6`.`test_model5_id`\s+=\s+\({\$__cakeID__\$}\)/', $result);
1559
 
1560
		$result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
1561
		$this->assertRegExp('/^SELECT\s+`TestModel5`\.`id`, `TestModel5`\.`test_model4_id`, `TestModel5`\.`name`, `TestModel5`\.`created`, `TestModel5`\.`updated`\s+/', $result);
1562
		$this->assertRegExp('/\s+FROM\s+\S+`test_model5` AS `TestModel5`\s+WHERE\s+/', $result);
1563
		$this->assertRegExp('/\s+WHERE\s+(?:\()?\s*1 = 1\s*(?:\))?\s*$/', $result);
1564
	}
1565
 
1566
/**
1567
 * testGenerateAssociationQueryHasManyWithLimit method
1568
 *
1569
 * @return void
1570
 */
1571
	public function testGenerateAssociationQueryHasManyWithLimit() {
1572
		$this->Model = new TestModel5();
1573
		$this->Model->schema();
1574
		$this->_buildRelatedModels($this->Model);
1575
 
1576
		$this->Model->hasMany['TestModel6']['limit'] = 2;
1577
 
1578
		$binding = array('type' => 'hasMany', 'model' => 'TestModel6');
1579
		$queryData = array();
1580
		$resultSet = null;
1581
		$null = null;
1582
 
1583
		$params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
1584
 
1585
		$result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
1586
		$this->assertRegExp(
1587
			'/^SELECT\s+' .
1588
			'`TestModel6`\.`id`, `TestModel6`\.`test_model5_id`, `TestModel6`\.`name`, `TestModel6`\.`created`, `TestModel6`\.`updated`\s+' .
1589
			'FROM\s+\S+`test_model6` AS `TestModel6`\s+WHERE\s+' .
1590
			'`TestModel6`.`test_model5_id`\s+=\s+\({\$__cakeID__\$}\)\s*' .
1591
			'LIMIT \d*' .
1592
			'\s*$/', $result
1593
		);
1594
 
1595
		$result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
1596
		$this->assertRegExp(
1597
			'/^SELECT\s+' .
1598
			'`TestModel5`\.`id`, `TestModel5`\.`test_model4_id`, `TestModel5`\.`name`, `TestModel5`\.`created`, `TestModel5`\.`updated`\s+' .
1599
			'FROM\s+\S+`test_model5` AS `TestModel5`\s+WHERE\s+' .
1600
			'(?:\()?\s*1 = 1\s*(?:\))?' .
1601
			'\s*$/', $result
1602
		);
1603
	}
1604
 
1605
/**
1606
 * testGenerateAssociationQueryHasManyWithConditions method
1607
 *
1608
 * @return void
1609
 */
1610
	public function testGenerateAssociationQueryHasManyWithConditions() {
1611
		$this->Model = new TestModel5();
1612
		$this->Model->schema();
1613
		$this->_buildRelatedModels($this->Model);
1614
 
1615
		$binding = array('type' => 'hasMany', 'model' => 'TestModel6');
1616
		$queryData = array('conditions' => array('TestModel5.name !=' => 'mariano'));
1617
		$resultSet = null;
1618
		$null = null;
1619
 
1620
		$params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
1621
 
1622
		$result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
1623
		$this->assertRegExp('/^SELECT\s+`TestModel6`\.`id`, `TestModel6`\.`test_model5_id`, `TestModel6`\.`name`, `TestModel6`\.`created`, `TestModel6`\.`updated`\s+/', $result);
1624
		$this->assertRegExp('/\s+FROM\s+\S+`test_model6` AS `TestModel6`\s+WHERE\s+/', $result);
1625
		$this->assertRegExp('/WHERE\s+(?:\()?`TestModel6`\.`test_model5_id`\s+=\s+\({\$__cakeID__\$}\)(?:\))?/', $result);
1626
 
1627
		$result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
1628
		$this->assertRegExp('/^SELECT\s+`TestModel5`\.`id`, `TestModel5`\.`test_model4_id`, `TestModel5`\.`name`, `TestModel5`\.`created`, `TestModel5`\.`updated`\s+/', $result);
1629
		$this->assertRegExp('/\s+FROM\s+\S+`test_model5` AS `TestModel5`\s+WHERE\s+/', $result);
1630
		$this->assertRegExp('/\s+WHERE\s+(?:\()?`TestModel5`.`name`\s+!=\s+\'mariano\'(?:\))?\s*$/', $result);
1631
	}
1632
 
1633
/**
1634
 * testGenerateAssociationQueryHasManyWithOffsetAndLimit method
1635
 *
1636
 * @return void
1637
 */
1638
	public function testGenerateAssociationQueryHasManyWithOffsetAndLimit() {
1639
		$this->Model = new TestModel5();
1640
		$this->Model->schema();
1641
		$this->_buildRelatedModels($this->Model);
1642
 
1643
		$backup = $this->Model->hasMany['TestModel6'];
1644
 
1645
		$this->Model->hasMany['TestModel6']['offset'] = 2;
1646
		$this->Model->hasMany['TestModel6']['limit'] = 5;
1647
 
1648
		$binding = array('type' => 'hasMany', 'model' => 'TestModel6');
1649
		$queryData = array();
1650
		$resultSet = null;
1651
		$null = null;
1652
 
1653
		$params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
1654
 
1655
		$result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
1656
 
1657
		$this->assertRegExp('/^SELECT\s+`TestModel6`\.`id`, `TestModel6`\.`test_model5_id`, `TestModel6`\.`name`, `TestModel6`\.`created`, `TestModel6`\.`updated`\s+/', $result);
1658
		$this->assertRegExp('/\s+FROM\s+\S+`test_model6` AS `TestModel6`\s+WHERE\s+/', $result);
1659
		$this->assertRegExp('/WHERE\s+(?:\()?`TestModel6`\.`test_model5_id`\s+=\s+\({\$__cakeID__\$}\)(?:\))?/', $result);
1660
		$this->assertRegExp('/\s+LIMIT 2,\s*5\s*$/', $result);
1661
 
1662
		$result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
1663
		$this->assertRegExp('/^SELECT\s+`TestModel5`\.`id`, `TestModel5`\.`test_model4_id`, `TestModel5`\.`name`, `TestModel5`\.`created`, `TestModel5`\.`updated`\s+/', $result);
1664
		$this->assertRegExp('/\s+FROM\s+\S+`test_model5` AS `TestModel5`\s+WHERE\s+/', $result);
1665
		$this->assertRegExp('/\s+WHERE\s+(?:\()?1\s+=\s+1(?:\))?\s*$/', $result);
1666
 
1667
		$this->Model->hasMany['TestModel6'] = $backup;
1668
	}
1669
 
1670
/**
1671
 * testGenerateAssociationQueryHasManyWithPageAndLimit method
1672
 *
1673
 * @return void
1674
 */
1675
	public function testGenerateAssociationQueryHasManyWithPageAndLimit() {
1676
		$this->Model = new TestModel5();
1677
		$this->Model->schema();
1678
		$this->_buildRelatedModels($this->Model);
1679
 
1680
		$backup = $this->Model->hasMany['TestModel6'];
1681
 
1682
		$this->Model->hasMany['TestModel6']['page'] = 2;
1683
		$this->Model->hasMany['TestModel6']['limit'] = 5;
1684
 
1685
		$binding = array('type' => 'hasMany', 'model' => 'TestModel6');
1686
		$queryData = array();
1687
		$resultSet = null;
1688
		$null = null;
1689
 
1690
		$params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
1691
 
1692
		$result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
1693
		$this->assertRegExp('/^SELECT\s+`TestModel6`\.`id`, `TestModel6`\.`test_model5_id`, `TestModel6`\.`name`, `TestModel6`\.`created`, `TestModel6`\.`updated`\s+/', $result);
1694
		$this->assertRegExp('/\s+FROM\s+\S+`test_model6` AS `TestModel6`\s+WHERE\s+/', $result);
1695
		$this->assertRegExp('/WHERE\s+(?:\()?`TestModel6`\.`test_model5_id`\s+=\s+\({\$__cakeID__\$}\)(?:\))?/', $result);
1696
		$this->assertRegExp('/\s+LIMIT 5,\s*5\s*$/', $result);
1697
 
1698
		$result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
1699
		$this->assertRegExp('/^SELECT\s+`TestModel5`\.`id`, `TestModel5`\.`test_model4_id`, `TestModel5`\.`name`, `TestModel5`\.`created`, `TestModel5`\.`updated`\s+/', $result);
1700
		$this->assertRegExp('/\s+FROM\s+\S+`test_model5` AS `TestModel5`\s+WHERE\s+/', $result);
1701
		$this->assertRegExp('/\s+WHERE\s+(?:\()?1\s+=\s+1(?:\))?\s*$/', $result);
1702
 
1703
		$this->Model->hasMany['TestModel6'] = $backup;
1704
	}
1705
 
1706
/**
1707
 * testGenerateAssociationQueryHasManyWithFields method
1708
 *
1709
 * @return void
1710
 */
1711
	public function testGenerateAssociationQueryHasManyWithFields() {
1712
		$this->Model = new TestModel5();
1713
		$this->Model->schema();
1714
		$this->_buildRelatedModels($this->Model);
1715
 
1716
		$binding = array('type' => 'hasMany', 'model' => 'TestModel6');
1717
		$queryData = array('fields' => array('`TestModel5`.`name`'));
1718
		$resultSet = null;
1719
		$null = null;
1720
 
1721
		$params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
1722
 
1723
		$result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
1724
		$this->assertRegExp('/^SELECT\s+`TestModel6`\.`id`, `TestModel6`\.`test_model5_id`, `TestModel6`\.`name`, `TestModel6`\.`created`, `TestModel6`\.`updated`\s+/', $result);
1725
		$this->assertRegExp('/\s+FROM\s+\S+`test_model6` AS `TestModel6`\s+WHERE\s+/', $result);
1726
		$this->assertRegExp('/WHERE\s+(?:\()?`TestModel6`\.`test_model5_id`\s+=\s+\({\$__cakeID__\$}\)(?:\))?/', $result);
1727
 
1728
		$result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
1729
		$this->assertRegExp('/^SELECT\s+`TestModel5`\.`name`, `TestModel5`\.`id`\s+/', $result);
1730
		$this->assertRegExp('/\s+FROM\s+\S+`test_model5` AS `TestModel5`\s+WHERE\s+/', $result);
1731
		$this->assertRegExp('/\s+WHERE\s+(?:\()?1\s+=\s+1(?:\))?\s*$/', $result);
1732
 
1733
		$binding = array('type' => 'hasMany', 'model' => 'TestModel6');
1734
		$queryData = array('fields' => array('`TestModel5`.`id`, `TestModel5`.`name`'));
1735
		$resultSet = null;
1736
		$null = null;
1737
 
1738
		$params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
1739
 
1740
		$result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
1741
		$this->assertRegExp('/^SELECT\s+`TestModel6`\.`id`, `TestModel6`\.`test_model5_id`, `TestModel6`\.`name`, `TestModel6`\.`created`, `TestModel6`\.`updated`\s+/', $result);
1742
		$this->assertRegExp('/\s+FROM\s+\S+`test_model6` AS `TestModel6`\s+WHERE\s+/', $result);
1743
		$this->assertRegExp('/WHERE\s+(?:\()?`TestModel6`\.`test_model5_id`\s+=\s+\({\$__cakeID__\$}\)(?:\))?/', $result);
1744
 
1745
		$result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
1746
		$this->assertRegExp('/^SELECT\s+`TestModel5`\.`id`, `TestModel5`\.`name`\s+/', $result);
1747
		$this->assertRegExp('/\s+FROM\s+\S+`test_model5` AS `TestModel5`\s+WHERE\s+/', $result);
1748
		$this->assertRegExp('/\s+WHERE\s+(?:\()?1\s+=\s+1(?:\))?\s*$/', $result);
1749
 
1750
		$binding = array('type' => 'hasMany', 'model' => 'TestModel6');
1751
		$queryData = array('fields' => array('`TestModel5`.`name`', '`TestModel5`.`created`'));
1752
		$resultSet = null;
1753
		$null = null;
1754
 
1755
		$params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
1756
 
1757
		$result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
1758
		$this->assertRegExp('/^SELECT\s+`TestModel6`\.`id`, `TestModel6`\.`test_model5_id`, `TestModel6`\.`name`, `TestModel6`\.`created`, `TestModel6`\.`updated`\s+/', $result);
1759
		$this->assertRegExp('/\s+FROM\s+\S+`test_model6` AS `TestModel6`\s+WHERE\s+/', $result);
1760
		$this->assertRegExp('/WHERE\s+(?:\()?`TestModel6`\.`test_model5_id`\s+=\s+\({\$__cakeID__\$}\)(?:\))?/', $result);
1761
 
1762
		$result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
1763
		$this->assertRegExp('/^SELECT\s+`TestModel5`\.`name`, `TestModel5`\.`created`, `TestModel5`\.`id`\s+/', $result);
1764
		$this->assertRegExp('/\s+FROM\s+\S+`test_model5` AS `TestModel5`\s+WHERE\s+/', $result);
1765
		$this->assertRegExp('/\s+WHERE\s+(?:\()?1\s+=\s+1(?:\))?\s*$/', $result);
1766
 
1767
		$this->Model->hasMany['TestModel6']['fields'] = array('name');
1768
 
1769
		$binding = array('type' => 'hasMany', 'model' => 'TestModel6');
1770
		$queryData = array('fields' => array('`TestModel5`.`id`', '`TestModel5`.`name`'));
1771
		$resultSet = null;
1772
		$null = null;
1773
 
1774
		$params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
1775
 
1776
		$result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
1777
		$this->assertRegExp('/^SELECT\s+`TestModel6`\.`name`, `TestModel6`\.`test_model5_id`\s+/', $result);
1778
		$this->assertRegExp('/\s+FROM\s+\S+`test_model6` AS `TestModel6`\s+WHERE\s+/', $result);
1779
		$this->assertRegExp('/WHERE\s+(?:\()?`TestModel6`\.`test_model5_id`\s+=\s+\({\$__cakeID__\$}\)(?:\))?/', $result);
1780
 
1781
		$result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
1782
		$this->assertRegExp('/^SELECT\s+`TestModel5`\.`id`, `TestModel5`\.`name`\s+/', $result);
1783
		$this->assertRegExp('/\s+FROM\s+\S+`test_model5` AS `TestModel5`\s+WHERE\s+/', $result);
1784
		$this->assertRegExp('/\s+WHERE\s+(?:\()?1\s+=\s+1(?:\))?\s*$/', $result);
1785
 
1786
		unset($this->Model->hasMany['TestModel6']['fields']);
1787
 
1788
		$this->Model->hasMany['TestModel6']['fields'] = array('id', 'name');
1789
 
1790
		$binding = array('type' => 'hasMany', 'model' => 'TestModel6');
1791
		$queryData = array('fields' => array('`TestModel5`.`id`', '`TestModel5`.`name`'));
1792
		$resultSet = null;
1793
		$null = null;
1794
 
1795
		$params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
1796
 
1797
		$result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
1798
		$this->assertRegExp('/^SELECT\s+`TestModel6`\.`id`, `TestModel6`\.`name`, `TestModel6`\.`test_model5_id`\s+/', $result);
1799
		$this->assertRegExp('/\s+FROM\s+\S+`test_model6` AS `TestModel6`\s+WHERE\s+/', $result);
1800
		$this->assertRegExp('/WHERE\s+(?:\()?`TestModel6`\.`test_model5_id`\s+=\s+\({\$__cakeID__\$}\)(?:\))?/', $result);
1801
 
1802
		$result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
1803
		$this->assertRegExp('/^SELECT\s+`TestModel5`\.`id`, `TestModel5`\.`name`\s+/', $result);
1804
		$this->assertRegExp('/\s+FROM\s+\S+`test_model5` AS `TestModel5`\s+WHERE\s+/', $result);
1805
		$this->assertRegExp('/\s+WHERE\s+(?:\()?1\s+=\s+1(?:\))?\s*$/', $result);
1806
 
1807
		unset($this->Model->hasMany['TestModel6']['fields']);
1808
 
1809
		$this->Model->hasMany['TestModel6']['fields'] = array('test_model5_id', 'name');
1810
 
1811
		$binding = array('type' => 'hasMany', 'model' => 'TestModel6');
1812
		$queryData = array('fields' => array('`TestModel5`.`id`', '`TestModel5`.`name`'));
1813
		$resultSet = null;
1814
		$null = null;
1815
 
1816
		$params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
1817
 
1818
		$result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
1819
		$this->assertRegExp('/^SELECT\s+`TestModel6`\.`test_model5_id`, `TestModel6`\.`name`\s+/', $result);
1820
		$this->assertRegExp('/\s+FROM\s+\S+`test_model6` AS `TestModel6`\s+WHERE\s+/', $result);
1821
		$this->assertRegExp('/WHERE\s+(?:\()?`TestModel6`\.`test_model5_id`\s+=\s+\({\$__cakeID__\$}\)(?:\))?/', $result);
1822
 
1823
		$result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
1824
		$this->assertRegExp('/^SELECT\s+`TestModel5`\.`id`, `TestModel5`\.`name`\s+/', $result);
1825
		$this->assertRegExp('/\s+FROM\s+\S+`test_model5` AS `TestModel5`\s+WHERE\s+/', $result);
1826
		$this->assertRegExp('/\s+WHERE\s+(?:\()?1\s+=\s+1(?:\))?\s*$/', $result);
1827
 
1828
		unset($this->Model->hasMany['TestModel6']['fields']);
1829
	}
1830
 
1831
/**
1832
 * test generateAssociationQuery with a hasMany and an aggregate function.
1833
 *
1834
 * @return void
1835
 */
1836
	public function testGenerateAssociationQueryHasManyAndAggregateFunction() {
1837
		$this->Model = new TestModel5();
1838
		$this->Model->schema();
1839
		$this->_buildRelatedModels($this->Model);
1840
 
1841
		$binding = array('type' => 'hasMany', 'model' => 'TestModel6');
1842
		$queryData = array('fields' => array('MIN(`TestModel5`.`test_model4_id`)'));
1843
		$resultSet = null;
1844
		$null = null;
1845
 
1846
		$params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
1847
		$this->Model->recursive = 0;
1848
 
1849
		$result = $this->Dbo->generateAssociationQuery($this->Model, $null, $params['type'], $params['assoc'], $params['assocData'], $queryData, false, $resultSet);
1850
		$this->assertRegExp('/^SELECT\s+MIN\(`TestModel5`\.`test_model4_id`\)\s+FROM/', $result);
1851
	}
1852
 
1853
/**
1854
 * testGenerateAssociationQueryHasAndBelongsToMany method
1855
 *
1856
 * @return void
1857
 */
1858
	public function testGenerateAssociationQueryHasAndBelongsToMany() {
1859
		$this->Model = new TestModel4();
1860
		$this->Model->schema();
1861
		$this->_buildRelatedModels($this->Model);
1862
 
1863
		$binding = array('type' => 'hasAndBelongsToMany', 'model' => 'TestModel7');
1864
		$queryData = array();
1865
		$resultSet = null;
1866
		$null = null;
1867
 
1868
		$params = $this->_prepareAssociationQuery($this->Model, $queryData, $binding);
1869
 
1870
		$result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
1871
		$assocTable = $this->Dbo->fullTableName($this->Model->TestModel4TestModel7, true, true);
1872
		$this->assertRegExp('/^SELECT\s+`TestModel7`\.`id`, `TestModel7`\.`name`, `TestModel7`\.`created`, `TestModel7`\.`updated`, `TestModel4TestModel7`\.`test_model4_id`, `TestModel4TestModel7`\.`test_model7_id`\s+/', $result);
1873
		$this->assertRegExp('/\s+FROM\s+\S+`test_model7` AS `TestModel7`\s+JOIN\s+' . $assocTable . '/', $result);
1874
		$this->assertRegExp('/\s+ON\s+\(`TestModel4TestModel7`\.`test_model4_id`\s+=\s+{\$__cakeID__\$}\s+AND/', $result);
1875
		$this->assertRegExp('/\s+AND\s+`TestModel4TestModel7`\.`test_model7_id`\s+=\s+`TestModel7`\.`id`\)/', $result);
1876
		$this->assertRegExp('/WHERE\s+(?:\()?1 = 1(?:\))?\s*$/', $result);
1877
 
1878
		$result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
1879
		$this->assertRegExp('/^SELECT\s+`TestModel4`\.`id`, `TestModel4`\.`name`, `TestModel4`\.`created`, `TestModel4`\.`updated`\s+/', $result);
1880
		$this->assertRegExp('/\s+FROM\s+\S+`test_model4` AS `TestModel4`\s+WHERE/', $result);
1881
		$this->assertRegExp('/\s+WHERE\s+(?:\()?1 = 1(?:\))?\s*$/', $result);
1882
	}
1883
 
1884
/**
1885
 * testGenerateAssociationQueryHasAndBelongsToManyWithConditions method
1886
 *
1887
 * @return void
1888
 */
1889
	public function testGenerateAssociationQueryHasAndBelongsToManyWithConditions() {
1890
		$this->Model = new TestModel4();
1891
		$this->Model->schema();
1892
		$this->_buildRelatedModels($this->Model);
1893
 
1894
		$binding = array('type' => 'hasAndBelongsToMany', 'model' => 'TestModel7');
1895
		$queryData = array('conditions' => array('TestModel4.name !=' => 'mariano'));
1896
		$resultSet = null;
1897
		$null = null;
1898
 
1899
		$params = $this->_prepareAssociationQuery($this->Model, $queryData, $binding);
1900
 
1901
		$result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
1902
		$this->assertRegExp('/^SELECT\s+`TestModel7`\.`id`, `TestModel7`\.`name`, `TestModel7`\.`created`, `TestModel7`\.`updated`, `TestModel4TestModel7`\.`test_model4_id`, `TestModel4TestModel7`\.`test_model7_id`\s+/', $result);
1903
		$this->assertRegExp('/\s+FROM\s+\S+`test_model7`\s+AS\s+`TestModel7`\s+JOIN\s+\S+`test_model4_test_model7`\s+AS\s+`TestModel4TestModel7`/', $result);
1904
		$this->assertRegExp('/\s+ON\s+\(`TestModel4TestModel7`\.`test_model4_id`\s+=\s+{\$__cakeID__\$}/', $result);
1905
		$this->assertRegExp('/\s+AND\s+`TestModel4TestModel7`\.`test_model7_id`\s+=\s+`TestModel7`\.`id`\)\s+WHERE\s+/', $result);
1906
 
1907
		$result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
1908
		$this->assertRegExp('/^SELECT\s+`TestModel4`\.`id`, `TestModel4`\.`name`, `TestModel4`\.`created`, `TestModel4`\.`updated`\s+/', $result);
1909
		$this->assertRegExp('/\s+FROM\s+\S+`test_model4` AS `TestModel4`\s+WHERE\s+(?:\()?`TestModel4`.`name`\s+!=\s+\'mariano\'(?:\))?\s*$/', $result);
1910
	}
1911
 
1912
/**
1913
 * testGenerateAssociationQueryHasAndBelongsToManyWithOffsetAndLimit method
1914
 *
1915
 * @return void
1916
 */
1917
	public function testGenerateAssociationQueryHasAndBelongsToManyWithOffsetAndLimit() {
1918
		$this->Model = new TestModel4();
1919
		$this->Model->schema();
1920
		$this->_buildRelatedModels($this->Model);
1921
 
1922
		$backup = $this->Model->hasAndBelongsToMany['TestModel7'];
1923
 
1924
		$this->Model->hasAndBelongsToMany['TestModel7']['offset'] = 2;
1925
		$this->Model->hasAndBelongsToMany['TestModel7']['limit'] = 5;
1926
 
1927
		$binding = array('type' => 'hasAndBelongsToMany', 'model' => 'TestModel7');
1928
		$queryData = array();
1929
		$resultSet = null;
1930
		$null = null;
1931
 
1932
		$params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
1933
 
1934
		$result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
1935
		$this->assertRegExp('/^SELECT\s+`TestModel7`\.`id`, `TestModel7`\.`name`, `TestModel7`\.`created`, `TestModel7`\.`updated`, `TestModel4TestModel7`\.`test_model4_id`, `TestModel4TestModel7`\.`test_model7_id`\s+/', $result);
1936
		$this->assertRegExp('/\s+FROM\s+\S+`test_model7`\s+AS\s+`TestModel7`\s+JOIN\s+\S+`test_model4_test_model7`\s+AS\s+`TestModel4TestModel7`/', $result);
1937
		$this->assertRegExp('/\s+ON\s+\(`TestModel4TestModel7`\.`test_model4_id`\s+=\s+{\$__cakeID__\$}\s+/', $result);
1938
		$this->assertRegExp('/\s+AND\s+`TestModel4TestModel7`\.`test_model7_id`\s+=\s+`TestModel7`\.`id`\)\s+WHERE\s+/', $result);
1939
		$this->assertRegExp('/\s+(?:\()?1\s+=\s+1(?:\))?\s*\s+LIMIT 2,\s*5\s*$/', $result);
1940
 
1941
		$result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
1942
		$this->assertRegExp('/^SELECT\s+`TestModel4`\.`id`, `TestModel4`\.`name`, `TestModel4`\.`created`, `TestModel4`\.`updated`\s+/', $result);
1943
		$this->assertRegExp('/\s+FROM\s+\S+`test_model4` AS `TestModel4`\s+WHERE\s+(?:\()?1\s+=\s+1(?:\))?\s*$/', $result);
1944
 
1945
		$this->Model->hasAndBelongsToMany['TestModel7'] = $backup;
1946
	}
1947
 
1948
/**
1949
 * testGenerateAssociationQueryHasAndBelongsToManyWithPageAndLimit method
1950
 *
1951
 * @return void
1952
 */
1953
	public function testGenerateAssociationQueryHasAndBelongsToManyWithPageAndLimit() {
1954
		$this->Model = new TestModel4();
1955
		$this->Model->schema();
1956
		$this->_buildRelatedModels($this->Model);
1957
 
1958
		$backup = $this->Model->hasAndBelongsToMany['TestModel7'];
1959
 
1960
		$this->Model->hasAndBelongsToMany['TestModel7']['page'] = 2;
1961
		$this->Model->hasAndBelongsToMany['TestModel7']['limit'] = 5;
1962
 
1963
		$binding = array('type' => 'hasAndBelongsToMany', 'model' => 'TestModel7');
1964
		$queryData = array();
1965
		$resultSet = null;
1966
		$null = null;
1967
 
1968
		$params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
1969
 
1970
		$result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
1971
		$this->assertRegExp('/^SELECT\s+`TestModel7`\.`id`, `TestModel7`\.`name`, `TestModel7`\.`created`, `TestModel7`\.`updated`, `TestModel4TestModel7`\.`test_model4_id`, `TestModel4TestModel7`\.`test_model7_id`\s+/', $result);
1972
		$this->assertRegExp('/\s+FROM\s+\S+`test_model7`\s+AS\s+`TestModel7`\s+JOIN\s+\S+`test_model4_test_model7`\s+AS\s+`TestModel4TestModel7`/', $result);
1973
		$this->assertRegExp('/\s+ON\s+\(`TestModel4TestModel7`\.`test_model4_id`\s+=\s+{\$__cakeID__\$}/', $result);
1974
		$this->assertRegExp('/\s+AND\s+`TestModel4TestModel7`\.`test_model7_id`\s+=\s+`TestModel7`\.`id`\)\s+WHERE\s+/', $result);
1975
		$this->assertRegExp('/\s+(?:\()?1\s+=\s+1(?:\))?\s*\s+LIMIT 5,\s*5\s*$/', $result);
1976
 
1977
		$result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
1978
		$this->assertRegExp('/^SELECT\s+`TestModel4`\.`id`, `TestModel4`\.`name`, `TestModel4`\.`created`, `TestModel4`\.`updated`\s+/', $result);
1979
		$this->assertRegExp('/\s+FROM\s+\S+`test_model4` AS `TestModel4`\s+WHERE\s+(?:\()?1\s+=\s+1(?:\))?\s*$/', $result);
1980
 
1981
		$this->Model->hasAndBelongsToMany['TestModel7'] = $backup;
1982
	}
1983
 
1984
/**
1985
 * testSelectDistict method
1986
 *
1987
 * @return void
1988
 */
1989
	public function testSelectDistict() {
1990
		$this->Model = new TestModel4();
1991
		$result = $this->Dbo->fields($this->Model, 'Vendor', "DISTINCT Vendor.id, Vendor.name");
1992
		$expected = array('DISTINCT `Vendor`.`id`', '`Vendor`.`name`');
1993
		$this->assertEquals($expected, $result);
1994
	}
1995
 
1996
/**
1997
 * testStringConditionsParsing method
1998
 *
1999
 * @return void
2000
 */
2001
	public function testStringConditionsParsing() {
2002
		$result = $this->Dbo->conditions("ProjectBid.project_id = Project.id");
2003
		$expected = " WHERE `ProjectBid`.`project_id` = `Project`.`id`";
2004
		$this->assertEquals($expected, $result);
2005
 
2006
		$result = $this->Dbo->conditions("Candy.name LIKE 'a' AND HardCandy.name LIKE 'c'");
2007
		$expected = " WHERE `Candy`.`name` LIKE 'a' AND `HardCandy`.`name` LIKE 'c'";
2008
		$this->assertEquals($expected, $result);
2009
 
2010
		$result = $this->Dbo->conditions("HardCandy.name LIKE 'a' AND Candy.name LIKE 'c'");
2011
		$expected = " WHERE `HardCandy`.`name` LIKE 'a' AND `Candy`.`name` LIKE 'c'";
2012
		$this->assertEquals($expected, $result);
2013
 
2014
		$result = $this->Dbo->conditions("Post.title = '1.1'");
2015
		$expected = " WHERE `Post`.`title` = '1.1'";
2016
		$this->assertEquals($expected, $result);
2017
 
2018
		$result = $this->Dbo->conditions("User.id != 0 AND User.user LIKE '%arr%'");
2019
		$expected = " WHERE `User`.`id` != 0 AND `User`.`user` LIKE '%arr%'";
2020
		$this->assertEquals($expected, $result);
2021
 
2022
		$result = $this->Dbo->conditions("SUM(Post.comments_count) > 500");
2023
		$expected = " WHERE SUM(`Post`.`comments_count`) > 500";
2024
		$this->assertEquals($expected, $result);
2025
 
2026
		$result = $this->Dbo->conditions("(Post.created < '" . date('Y-m-d H:i') . "') GROUP BY YEAR(Post.created), MONTH(Post.created)");
2027
		$expected = " WHERE (`Post`.`created` < '" . date('Y-m-d H:i') . "') GROUP BY YEAR(`Post`.`created`), MONTH(`Post`.`created`)";
2028
		$this->assertEquals($expected, $result);
2029
 
2030
		$result = $this->Dbo->conditions("score BETWEEN 90.1 AND 95.7");
2031
		$expected = " WHERE score BETWEEN 90.1 AND 95.7";
2032
		$this->assertEquals($expected, $result);
2033
 
2034
		$result = $this->Dbo->conditions(array('score' => array(2 => 1, 2, 10)));
2035
		$expected = " WHERE `score` IN (1, 2, 10)";
2036
		$this->assertEquals($expected, $result);
2037
 
2038
		$result = $this->Dbo->conditions("Aro.rght = Aro.lft + 1.1");
2039
		$expected = " WHERE `Aro`.`rght` = `Aro`.`lft` + 1.1";
2040
		$this->assertEquals($expected, $result);
2041
 
2042
		$result = $this->Dbo->conditions("(Post.created < '" . date('Y-m-d H:i:s') . "') GROUP BY YEAR(Post.created), MONTH(Post.created)");
2043
		$expected = " WHERE (`Post`.`created` < '" . date('Y-m-d H:i:s') . "') GROUP BY YEAR(`Post`.`created`), MONTH(`Post`.`created`)";
2044
		$this->assertEquals($expected, $result);
2045
 
2046
		$result = $this->Dbo->conditions('Sportstaette.sportstaette LIKE "%ru%" AND Sportstaette.sportstaettenart_id = 2');
2047
		$expected = ' WHERE `Sportstaette`.`sportstaette` LIKE "%ru%" AND `Sportstaette`.`sportstaettenart_id` = 2';
2048
		$this->assertRegExp('/\s*WHERE\s+`Sportstaette`\.`sportstaette`\s+LIKE\s+"%ru%"\s+AND\s+`Sports/', $result);
2049
		$this->assertEquals($expected, $result);
2050
 
2051
		$result = $this->Dbo->conditions('Sportstaette.sportstaettenart_id = 2 AND Sportstaette.sportstaette LIKE "%ru%"');
2052
		$expected = ' WHERE `Sportstaette`.`sportstaettenart_id` = 2 AND `Sportstaette`.`sportstaette` LIKE "%ru%"';
2053
		$this->assertEquals($expected, $result);
2054
 
2055
		$result = $this->Dbo->conditions('SUM(Post.comments_count) > 500 AND NOT Post.title IS NULL AND NOT Post.extended_title IS NULL');
2056
		$expected = ' WHERE SUM(`Post`.`comments_count`) > 500 AND NOT `Post`.`title` IS NULL AND NOT `Post`.`extended_title` IS NULL';
2057
		$this->assertEquals($expected, $result);
2058
 
2059
		$result = $this->Dbo->conditions('NOT Post.title IS NULL AND NOT Post.extended_title IS NULL AND SUM(Post.comments_count) > 500');
2060
		$expected = ' WHERE NOT `Post`.`title` IS NULL AND NOT `Post`.`extended_title` IS NULL AND SUM(`Post`.`comments_count`) > 500';
2061
		$this->assertEquals($expected, $result);
2062
 
2063
		$result = $this->Dbo->conditions('NOT Post.extended_title IS NULL AND NOT Post.title IS NULL AND Post.title != "" AND SPOON(SUM(Post.comments_count) + 1.1) > 500');
2064
		$expected = ' WHERE NOT `Post`.`extended_title` IS NULL AND NOT `Post`.`title` IS NULL AND `Post`.`title` != "" AND SPOON(SUM(`Post`.`comments_count`) + 1.1) > 500';
2065
		$this->assertEquals($expected, $result);
2066
 
2067
		$result = $this->Dbo->conditions('NOT Post.title_extended IS NULL AND NOT Post.title IS NULL AND Post.title_extended != Post.title');
2068
		$expected = ' WHERE NOT `Post`.`title_extended` IS NULL AND NOT `Post`.`title` IS NULL AND `Post`.`title_extended` != `Post`.`title`';
2069
		$this->assertEquals($expected, $result);
2070
 
2071
		$result = $this->Dbo->conditions("Comment.id = 'a'");
2072
		$expected = " WHERE `Comment`.`id` = 'a'";
2073
		$this->assertEquals($expected, $result);
2074
 
2075
		$result = $this->Dbo->conditions("lower(Article.title) LIKE 'a%'");
2076
		$expected = " WHERE lower(`Article`.`title`) LIKE 'a%'";
2077
		$this->assertEquals($expected, $result);
2078
 
2079
		$result = $this->Dbo->conditions('((MATCH(Video.title) AGAINST(\'My Search*\' IN BOOLEAN MODE) * 2) + (MATCH(Video.description) AGAINST(\'My Search*\' IN BOOLEAN MODE) * 0.4) + (MATCH(Video.tags) AGAINST(\'My Search*\' IN BOOLEAN MODE) * 1.5))');
2080
		$expected = ' WHERE ((MATCH(`Video`.`title`) AGAINST(\'My Search*\' IN BOOLEAN MODE) * 2) + (MATCH(`Video`.`description`) AGAINST(\'My Search*\' IN BOOLEAN MODE) * 0.4) + (MATCH(`Video`.`tags`) AGAINST(\'My Search*\' IN BOOLEAN MODE) * 1.5))';
2081
		$this->assertEquals($expected, $result);
2082
 
2083
		$result = $this->Dbo->conditions('DATEDIFF(NOW(),Article.published) < 1 && Article.live=1');
2084
		$expected = " WHERE DATEDIFF(NOW(),`Article`.`published`) < 1 && `Article`.`live`=1";
2085
		$this->assertEquals($expected, $result);
2086
 
2087
		$result = $this->Dbo->conditions('file = "index.html"');
2088
		$expected = ' WHERE file = "index.html"';
2089
		$this->assertEquals($expected, $result);
2090
 
2091
		$result = $this->Dbo->conditions("file = 'index.html'");
2092
		$expected = " WHERE file = 'index.html'";
2093
		$this->assertEquals($expected, $result);
2094
 
2095
		$letter = $letter = 'd.a';
2096
		$conditions = array('Company.name like ' => $letter . '%');
2097
		$result = $this->Dbo->conditions($conditions);
2098
		$expected = " WHERE `Company`.`name` like 'd.a%'";
2099
		$this->assertEquals($expected, $result);
2100
 
2101
		$conditions = array('Artist.name' => 'JUDY and MARY');
2102
		$result = $this->Dbo->conditions($conditions);
2103
		$expected = " WHERE `Artist`.`name` = 'JUDY and MARY'";
2104
		$this->assertEquals($expected, $result);
2105
 
2106
		$conditions = array('Artist.name' => 'JUDY AND MARY');
2107
		$result = $this->Dbo->conditions($conditions);
2108
		$expected = " WHERE `Artist`.`name` = 'JUDY AND MARY'";
2109
		$this->assertEquals($expected, $result);
2110
 
2111
		$conditions = array('Company.name similar to ' => 'a word');
2112
		$result = $this->Dbo->conditions($conditions);
2113
		$expected = " WHERE `Company`.`name` similar to 'a word'";
2114
		$this->assertEquals($expected, $result);
2115
	}
2116
 
2117
/**
2118
 * testQuotesInStringConditions method
2119
 *
2120
 * @return void
2121
 */
2122
	public function testQuotesInStringConditions() {
2123
		$result = $this->Dbo->conditions('Member.email = \'mariano@cricava.com\'');
2124
		$expected = ' WHERE `Member`.`email` = \'mariano@cricava.com\'';
2125
		$this->assertEquals($expected, $result);
2126
 
2127
		$result = $this->Dbo->conditions('Member.email = "mariano@cricava.com"');
2128
		$expected = ' WHERE `Member`.`email` = "mariano@cricava.com"';
2129
		$this->assertEquals($expected, $result);
2130
 
2131
		$result = $this->Dbo->conditions('Member.email = \'mariano@cricava.com\' AND Member.user LIKE \'mariano.iglesias%\'');
2132
		$expected = ' WHERE `Member`.`email` = \'mariano@cricava.com\' AND `Member`.`user` LIKE \'mariano.iglesias%\'';
2133
		$this->assertEquals($expected, $result);
2134
 
2135
		$result = $this->Dbo->conditions('Member.email = "mariano@cricava.com" AND Member.user LIKE "mariano.iglesias%"');
2136
		$expected = ' WHERE `Member`.`email` = "mariano@cricava.com" AND `Member`.`user` LIKE "mariano.iglesias%"';
2137
		$this->assertEquals($expected, $result);
2138
	}
2139
 
2140
/**
2141
 * test that - in conditions and field names works
2142
 *
2143
 * @return void
2144
 */
2145
	public function testHypenInStringConditionsAndFieldNames() {
2146
		$result = $this->Dbo->conditions('I18n__title_pt-br.content = "test"');
2147
		$this->assertEquals(' WHERE `I18n__title_pt-br`.`content` = "test"', $result);
2148
 
2149
		$result = $this->Dbo->conditions('Model.field=NOW()-3600');
2150
		$this->assertEquals(' WHERE `Model`.`field`=NOW()-3600', $result);
2151
 
2152
		$result = $this->Dbo->conditions('NOW() - Model.created < 7200');
2153
		$this->assertEquals(' WHERE NOW() - `Model`.`created` < 7200', $result);
2154
 
2155
		$result = $this->Dbo->conditions('NOW()-Model.created < 7200');
2156
		$this->assertEquals(' WHERE NOW()-`Model`.`created` < 7200', $result);
2157
	}
2158
 
2159
/**
2160
 * testParenthesisInStringConditions method
2161
 *
2162
 * @return void
2163
 */
2164
	public function testParenthesisInStringConditions() {
2165
		$result = $this->Dbo->conditions('Member.name = \'(lu\'');
2166
		$this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(lu\'$/', $result);
2167
 
2168
		$result = $this->Dbo->conditions('Member.name = \')lu\'');
2169
		$this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\)lu\'$/', $result);
2170
 
2171
		$result = $this->Dbo->conditions('Member.name = \'va(lu\'');
2172
		$this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'va\(lu\'$/', $result);
2173
 
2174
		$result = $this->Dbo->conditions('Member.name = \'va)lu\'');
2175
		$this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'va\)lu\'$/', $result);
2176
 
2177
		$result = $this->Dbo->conditions('Member.name = \'va(lu)\'');
2178
		$this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'va\(lu\)\'$/', $result);
2179
 
2180
		$result = $this->Dbo->conditions('Member.name = \'va(lu)e\'');
2181
		$this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'va\(lu\)e\'$/', $result);
2182
 
2183
		$result = $this->Dbo->conditions('Member.name = \'(mariano)\'');
2184
		$this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(mariano\)\'$/', $result);
2185
 
2186
		$result = $this->Dbo->conditions('Member.name = \'(mariano)iglesias\'');
2187
		$this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(mariano\)iglesias\'$/', $result);
2188
 
2189
		$result = $this->Dbo->conditions('Member.name = \'(mariano) iglesias\'');
2190
		$this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(mariano\) iglesias\'$/', $result);
2191
 
2192
		$result = $this->Dbo->conditions('Member.name = \'(mariano word) iglesias\'');
2193
		$this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(mariano word\) iglesias\'$/', $result);
2194
 
2195
		$result = $this->Dbo->conditions('Member.name = \'(mariano.iglesias)\'');
2196
		$this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(mariano.iglesias\)\'$/', $result);
2197
 
2198
		$result = $this->Dbo->conditions('Member.name = \'Mariano Iglesias (mariano.iglesias)\'');
2199
		$this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'Mariano Iglesias \(mariano.iglesias\)\'$/', $result);
2200
 
2201
		$result = $this->Dbo->conditions('Member.name = \'Mariano Iglesias (mariano.iglesias) CakePHP\'');
2202
		$this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'Mariano Iglesias \(mariano.iglesias\) CakePHP\'$/', $result);
2203
 
2204
		$result = $this->Dbo->conditions('Member.name = \'(mariano.iglesias) CakePHP\'');
2205
		$this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(mariano.iglesias\) CakePHP\'$/', $result);
2206
	}
2207
 
2208
/**
2209
 * testParenthesisInArrayConditions method
2210
 *
2211
 * @return void
2212
 */
2213
	public function testParenthesisInArrayConditions() {
2214
		$result = $this->Dbo->conditions(array('Member.name' => '(lu'));
2215
		$this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(lu\'$/', $result);
2216
 
2217
		$result = $this->Dbo->conditions(array('Member.name' => ')lu'));
2218
		$this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\)lu\'$/', $result);
2219
 
2220
		$result = $this->Dbo->conditions(array('Member.name' => 'va(lu'));
2221
		$this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'va\(lu\'$/', $result);
2222
 
2223
		$result = $this->Dbo->conditions(array('Member.name' => 'va)lu'));
2224
		$this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'va\)lu\'$/', $result);
2225
 
2226
		$result = $this->Dbo->conditions(array('Member.name' => 'va(lu)'));
2227
		$this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'va\(lu\)\'$/', $result);
2228
 
2229
		$result = $this->Dbo->conditions(array('Member.name' => 'va(lu)e'));
2230
		$this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'va\(lu\)e\'$/', $result);
2231
 
2232
		$result = $this->Dbo->conditions(array('Member.name' => '(mariano)'));
2233
		$this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(mariano\)\'$/', $result);
2234
 
2235
		$result = $this->Dbo->conditions(array('Member.name' => '(mariano)iglesias'));
2236
		$this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(mariano\)iglesias\'$/', $result);
2237
 
2238
		$result = $this->Dbo->conditions(array('Member.name' => '(mariano) iglesias'));
2239
		$this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(mariano\) iglesias\'$/', $result);
2240
 
2241
		$result = $this->Dbo->conditions(array('Member.name' => '(mariano word) iglesias'));
2242
		$this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(mariano word\) iglesias\'$/', $result);
2243
 
2244
		$result = $this->Dbo->conditions(array('Member.name' => '(mariano.iglesias)'));
2245
		$this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(mariano.iglesias\)\'$/', $result);
2246
 
2247
		$result = $this->Dbo->conditions(array('Member.name' => 'Mariano Iglesias (mariano.iglesias)'));
2248
		$this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'Mariano Iglesias \(mariano.iglesias\)\'$/', $result);
2249
 
2250
		$result = $this->Dbo->conditions(array('Member.name' => 'Mariano Iglesias (mariano.iglesias) CakePHP'));
2251
		$this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'Mariano Iglesias \(mariano.iglesias\) CakePHP\'$/', $result);
2252
 
2253
		$result = $this->Dbo->conditions(array('Member.name' => '(mariano.iglesias) CakePHP'));
2254
		$this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(mariano.iglesias\) CakePHP\'$/', $result);
2255
	}
2256
 
2257
/**
2258
 * testArrayConditionsParsing method
2259
 *
2260
 * @return void
2261
 */
2262
	public function testArrayConditionsParsing() {
2263
		$this->loadFixtures('Post', 'Author');
2264
		$result = $this->Dbo->conditions(array('Stereo.type' => 'in dash speakers'));
2265
		$this->assertRegExp("/^\s+WHERE\s+`Stereo`.`type`\s+=\s+'in dash speakers'/", $result);
2266
 
2267
		$result = $this->Dbo->conditions(array('Candy.name LIKE' => 'a', 'HardCandy.name LIKE' => 'c'));
2268
		$this->assertRegExp("/^\s+WHERE\s+`Candy`.`name` LIKE\s+'a'\s+AND\s+`HardCandy`.`name`\s+LIKE\s+'c'/", $result);
2269
 
2270
		$result = $this->Dbo->conditions(array('HardCandy.name LIKE' => 'a', 'Candy.name LIKE' => 'c'));
2271
		$expected = " WHERE `HardCandy`.`name` LIKE 'a' AND `Candy`.`name` LIKE 'c'";
2272
		$this->assertEquals($expected, $result);
2273
 
2274
		$result = $this->Dbo->conditions(array('HardCandy.name LIKE' => 'a%', 'Candy.name LIKE' => '%c%'));
2275
		$expected = " WHERE `HardCandy`.`name` LIKE 'a%' AND `Candy`.`name` LIKE '%c%'";
2276
		$this->assertEquals($expected, $result);
2277
 
2278
		$result = $this->Dbo->conditions(array('HardCandy.name LIKE' => 'to be or%', 'Candy.name LIKE' => '%not to be%'));
2279
		$expected = " WHERE `HardCandy`.`name` LIKE 'to be or%' AND `Candy`.`name` LIKE '%not to be%'";
2280
		$this->assertEquals($expected, $result);
2281
 
2282
		$result = $this->Dbo->conditions(array(
2283
			"Person.name || ' ' || Person.surname ILIKE" => '%mark%'
2284
		));
2285
		$expected = " WHERE `Person`.`name` || ' ' || `Person`.`surname` ILIKE '%mark%'";
2286
		$this->assertEquals($expected, $result);
2287
 
2288
		$result = $this->Dbo->conditions(array('score BETWEEN ? AND ?' => array(90.1, 95.7)));
2289
		$expected = " WHERE `score` BETWEEN 90.1 AND 95.7";
2290
		$this->assertEquals($expected, $result);
2291
 
2292
		$result = $this->Dbo->conditions(array('Post.title' => 1.1));
2293
		$expected = " WHERE `Post`.`title` = 1.1";
2294
		$this->assertEquals($expected, $result);
2295
 
2296
		$result = $this->Dbo->conditions(array('Post.title' => 1.1), true, true, new Post());
2297
		$expected = " WHERE `Post`.`title` = '1.1'";
2298
		$this->assertEquals($expected, $result);
2299
 
2300
		$result = $this->Dbo->conditions(array('SUM(Post.comments_count) >' => '500'));
2301
		$expected = " WHERE SUM(`Post`.`comments_count`) > '500'";
2302
		$this->assertEquals($expected, $result);
2303
 
2304
		$result = $this->Dbo->conditions(array('MAX(Post.rating) >' => '50'));
2305
		$expected = " WHERE MAX(`Post`.`rating`) > '50'";
2306
		$this->assertEquals($expected, $result);
2307
 
2308
		$result = $this->Dbo->conditions(array('lower(Article.title)' => 'secrets'));
2309
		$expected = " WHERE lower(`Article`.`title`) = 'secrets'";
2310
		$this->assertEquals($expected, $result);
2311
 
2312
		$result = $this->Dbo->conditions(array('title LIKE' => '%hello'));
2313
		$expected = " WHERE `title` LIKE '%hello'";
2314
		$this->assertEquals($expected, $result);
2315
 
2316
		$result = $this->Dbo->conditions(array('Post.name' => 'mad(g)ik'));
2317
		$expected = " WHERE `Post`.`name` = 'mad(g)ik'";
2318
		$this->assertEquals($expected, $result);
2319
 
2320
		$result = $this->Dbo->conditions(array('score' => array(1, 2, 10)));
2321
		$expected = " WHERE `score` IN (1, 2, 10)";
2322
		$this->assertEquals($expected, $result);
2323
 
2324
		$result = $this->Dbo->conditions(array('score' => array()));
2325
		$expected = " WHERE `score` IS NULL";
2326
		$this->assertEquals($expected, $result);
2327
 
2328
		$result = $this->Dbo->conditions(array('score !=' => array()));
2329
		$expected = " WHERE `score` IS NOT NULL";
2330
		$this->assertEquals($expected, $result);
2331
 
2332
		$result = $this->Dbo->conditions(array('score !=' => '20'));
2333
		$expected = " WHERE `score` != '20'";
2334
		$this->assertEquals($expected, $result);
2335
 
2336
		$result = $this->Dbo->conditions(array('score >' => '20'));
2337
		$expected = " WHERE `score` > '20'";
2338
		$this->assertEquals($expected, $result);
2339
 
2340
		$result = $this->Dbo->conditions(array('client_id >' => '20'), true, true, new TestModel());
2341
		$expected = " WHERE `client_id` > 20";
2342
		$this->assertEquals($expected, $result);
2343
 
2344
		$result = $this->Dbo->conditions(array('OR' => array(
2345
			array('User.user' => 'mariano'),
2346
			array('User.user' => 'nate')
2347
		)));
2348
 
2349
		$expected = " WHERE ((`User`.`user` = 'mariano') OR (`User`.`user` = 'nate'))";
2350
		$this->assertEquals($expected, $result);
2351
 
2352
		$result = $this->Dbo->conditions(array('or' => array(
2353
			'score BETWEEN ? AND ?' => array('4', '5'), 'rating >' => '20'
2354
		)));
2355
		$expected = " WHERE ((`score` BETWEEN '4' AND '5') OR (`rating` > '20'))";
2356
		$this->assertEquals($expected, $result);
2357
 
2358
		$result = $this->Dbo->conditions(array('or' => array(
2359
			'score BETWEEN ? AND ?' => array('4', '5'), array('score >' => '20')
2360
		)));
2361
		$expected = " WHERE ((`score` BETWEEN '4' AND '5') OR (`score` > '20'))";
2362
		$this->assertEquals($expected, $result);
2363
 
2364
		$result = $this->Dbo->conditions(array('and' => array(
2365
			'score BETWEEN ? AND ?' => array('4', '5'), array('score >' => '20')
2366
		)));
2367
		$expected = " WHERE ((`score` BETWEEN '4' AND '5') AND (`score` > '20'))";
2368
		$this->assertEquals($expected, $result);
2369
 
2370
		$result = $this->Dbo->conditions(array(
2371
			'published' => 1, 'or' => array('score >' => '2', array('score >' => '20'))
2372
		));
2373
		$expected = " WHERE `published` = 1 AND ((`score` > '2') OR (`score` > '20'))";
2374
		$this->assertEquals($expected, $result);
2375
 
2376
		$result = $this->Dbo->conditions(array(array('Project.removed' => false)));
2377
		$expected = " WHERE `Project`.`removed` = '0'";
2378
		$this->assertEquals($expected, $result);
2379
 
2380
		$result = $this->Dbo->conditions(array(array('Project.removed' => true)));
2381
		$expected = " WHERE `Project`.`removed` = '1'";
2382
		$this->assertEquals($expected, $result);
2383
 
2384
		$result = $this->Dbo->conditions(array(array('Project.removed' => null)));
2385
		$expected = " WHERE `Project`.`removed` IS NULL";
2386
		$this->assertEquals($expected, $result);
2387
 
2388
		$result = $this->Dbo->conditions(array(array('Project.removed !=' => null)));
2389
		$expected = " WHERE `Project`.`removed` IS NOT NULL";
2390
		$this->assertEquals($expected, $result);
2391
 
2392
		$result = $this->Dbo->conditions(array('(Usergroup.permissions) & 4' => 4));
2393
		$expected = " WHERE (`Usergroup`.`permissions`) & 4 = 4";
2394
		$this->assertEquals($expected, $result);
2395
 
2396
		$result = $this->Dbo->conditions(array('((Usergroup.permissions) & 4)' => 4));
2397
		$expected = " WHERE ((`Usergroup`.`permissions`) & 4) = 4";
2398
		$this->assertEquals($expected, $result);
2399
 
2400
		$result = $this->Dbo->conditions(array('Post.modified >=' => 'DATE_SUB(NOW(), INTERVAL 7 DAY)'));
2401
		$expected = " WHERE `Post`.`modified` >= 'DATE_SUB(NOW(), INTERVAL 7 DAY)'";
2402
		$this->assertEquals($expected, $result);
2403
 
2404
		$result = $this->Dbo->conditions(array('Post.modified >= DATE_SUB(NOW(), INTERVAL 7 DAY)'));
2405
		$expected = " WHERE `Post`.`modified` >= DATE_SUB(NOW(), INTERVAL 7 DAY)";
2406
		$this->assertEquals($expected, $result);
2407
 
2408
		$result = $this->Dbo->conditions(array(
2409
			'NOT' => array('Course.id' => null, 'Course.vet' => 'N', 'level_of_education_id' => array(912, 999)),
2410
			'Enrollment.yearcompleted >' => '0')
2411
		);
2412
		$this->assertRegExp('/^\s*WHERE\s+\(NOT\s+\(`Course`\.`id` IS NULL\)\s+AND NOT\s+\(`Course`\.`vet`\s+=\s+\'N\'\)\s+AND NOT\s+\(`level_of_education_id` IN \(912, 999\)\)\)\s+AND\s+`Enrollment`\.`yearcompleted`\s+>\s+\'0\'\s*$/', $result);
2413
 
2414
		$result = $this->Dbo->conditions(array('id <>' => '8'));
2415
		$this->assertRegExp('/^\s*WHERE\s+`id`\s+<>\s+\'8\'\s*$/', $result);
2416
 
2417
		$result = $this->Dbo->conditions(array('TestModel.field =' => 'gribe$@()lu'));
2418
		$expected = " WHERE `TestModel`.`field` = 'gribe$@()lu'";
2419
		$this->assertEquals($expected, $result);
2420
 
2421
		$conditions['NOT'] = array('Listing.expiration BETWEEN ? AND ?' => array("1", "100"));
2422
		$conditions[0]['OR'] = array(
2423
			"Listing.title LIKE" => "%term%",
2424
			"Listing.description LIKE" => "%term%"
2425
		);
2426
		$conditions[1]['OR'] = array(
2427
			"Listing.title LIKE" => "%term_2%",
2428
			"Listing.description LIKE" => "%term_2%"
2429
		);
2430
		$result = $this->Dbo->conditions($conditions);
2431
		$expected = " WHERE NOT (`Listing`.`expiration` BETWEEN '1' AND '100') AND" .
2432
		" ((`Listing`.`title` LIKE '%term%') OR (`Listing`.`description` LIKE '%term%')) AND" .
2433
		" ((`Listing`.`title` LIKE '%term_2%') OR (`Listing`.`description` LIKE '%term_2%'))";
2434
		$this->assertEquals($expected, $result);
2435
 
2436
		$result = $this->Dbo->conditions(array('MD5(CONCAT(Reg.email,Reg.id))' => 'blah'));
2437
		$expected = " WHERE MD5(CONCAT(`Reg`.`email`,`Reg`.`id`)) = 'blah'";
2438
		$this->assertEquals($expected, $result);
2439
 
2440
		$result = $this->Dbo->conditions(array(
2441
			'MD5(CONCAT(Reg.email,Reg.id))' => array('blah', 'blahblah')
2442
		));
2443
		$expected = " WHERE MD5(CONCAT(`Reg`.`email`,`Reg`.`id`)) IN ('blah', 'blahblah')";
2444
		$this->assertEquals($expected, $result);
2445
 
2446
		$conditions = array('id' => array(2, 5, 6, 9, 12, 45, 78, 43, 76));
2447
		$result = $this->Dbo->conditions($conditions);
2448
		$expected = " WHERE `id` IN (2, 5, 6, 9, 12, 45, 78, 43, 76)";
2449
		$this->assertEquals($expected, $result);
2450
 
2451
		$conditions = array('`Correction`.`source` collate utf8_bin' => array('kiwi', 'pear'));
2452
		$result = $this->Dbo->conditions($conditions);
2453
		$expected = " WHERE `Correction`.`source` collate utf8_bin IN ('kiwi', 'pear')";
2454
		$this->assertEquals($expected, $result);
2455
 
2456
		$conditions = array('title' => 'user(s)');
2457
		$result = $this->Dbo->conditions($conditions);
2458
		$expected = " WHERE `title` = 'user(s)'";
2459
		$this->assertEquals($expected, $result);
2460
 
2461
		$conditions = array('title' => 'user(s) data');
2462
		$result = $this->Dbo->conditions($conditions);
2463
		$expected = " WHERE `title` = 'user(s) data'";
2464
		$this->assertEquals($expected, $result);
2465
 
2466
		$conditions = array('title' => 'user(s,arg) data');
2467
		$result = $this->Dbo->conditions($conditions);
2468
		$expected = " WHERE `title` = 'user(s,arg) data'";
2469
		$this->assertEquals($expected, $result);
2470
 
2471
		$result = $this->Dbo->conditions(array("Book.book_name" => 'Java(TM)'));
2472
		$expected = " WHERE `Book`.`book_name` = 'Java(TM)'";
2473
		$this->assertEquals($expected, $result);
2474
 
2475
		$result = $this->Dbo->conditions(array("Book.book_name" => 'Java(TM) '));
2476
		$expected = " WHERE `Book`.`book_name` = 'Java(TM) '";
2477
		$this->assertEquals($expected, $result);
2478
 
2479
		$result = $this->Dbo->conditions(array("Book.id" => 0));
2480
		$expected = " WHERE `Book`.`id` = 0";
2481
		$this->assertEquals($expected, $result);
2482
 
2483
		$result = $this->Dbo->conditions(array("Book.id" => null));
2484
		$expected = " WHERE `Book`.`id` IS NULL";
2485
		$this->assertEquals($expected, $result);
2486
 
2487
		$conditions = array('MysqlModel.id' => '');
2488
		$result = $this->Dbo->conditions($conditions, true, true, $this->model);
2489
		$expected = " WHERE `MysqlModel`.`id` IS NULL";
2490
		$this->assertEquals($expected, $result);
2491
 
2492
		$result = $this->Dbo->conditions(array('Listing.beds >=' => 0));
2493
		$expected = " WHERE `Listing`.`beds` >= 0";
2494
		$this->assertEquals($expected, $result);
2495
 
2496
		$result = $this->Dbo->conditions(array(
2497
			'ASCII(SUBSTRING(keyword, 1, 1)) BETWEEN ? AND ?' => array(65, 90)
2498
		));
2499
		$expected = ' WHERE ASCII(SUBSTRING(keyword, 1, 1)) BETWEEN 65 AND 90';
2500
		$this->assertEquals($expected, $result);
2501
 
2502
		$result = $this->Dbo->conditions(array('or' => array(
2503
			'? BETWEEN Model.field1 AND Model.field2' => '2009-03-04'
2504
		)));
2505
		$expected = " WHERE '2009-03-04' BETWEEN Model.field1 AND Model.field2";
2506
		$this->assertEquals($expected, $result);
2507
	}
2508
 
2509
/**
2510
 * Test that array conditions with only one element work.
2511
 *
2512
 * @return void
2513
 */
2514
	public function testArrayConditionsOneElement() {
2515
		$conditions = array('id' => array(1));
2516
		$result = $this->Dbo->conditions($conditions);
2517
		$expected = " WHERE id = (1)";
2518
		$this->assertEquals($expected, $result);
2519
 
2520
		$conditions = array('id NOT' => array(1));
2521
		$result = $this->Dbo->conditions($conditions);
2522
		$expected = " WHERE NOT (id = (1))";
2523
		$this->assertEquals($expected, $result);
2524
	}
2525
 
2526
/**
2527
 * testArrayConditionsParsingComplexKeys method
2528
 *
2529
 * @return void
2530
 */
2531
	public function testArrayConditionsParsingComplexKeys() {
2532
		$result = $this->Dbo->conditions(array(
2533
			'CAST(Book.created AS DATE)' => '2008-08-02'
2534
		));
2535
		$expected = " WHERE CAST(`Book`.`created` AS DATE) = '2008-08-02'";
2536
		$this->assertEquals($expected, $result);
2537
 
2538
		$result = $this->Dbo->conditions(array(
2539
			'CAST(Book.created AS DATE) <=' => '2008-08-02'
2540
		));
2541
		$expected = " WHERE CAST(`Book`.`created` AS DATE) <= '2008-08-02'";
2542
		$this->assertEquals($expected, $result);
2543
 
2544
		$result = $this->Dbo->conditions(array(
2545
			'(Stats.clicks * 100) / Stats.views >' => 50
2546
		));
2547
		$expected = " WHERE (`Stats`.`clicks` * 100) / `Stats`.`views` > 50";
2548
		$this->assertEquals($expected, $result);
2549
	}
2550
 
2551
/**
2552
 * testMixedConditionsParsing method
2553
 *
2554
 * @return void
2555
 */
2556
	public function testMixedConditionsParsing() {
2557
		$conditions[] = 'User.first_name = \'Firstname\'';
2558
		$conditions[] = array('User.last_name' => 'Lastname');
2559
		$result = $this->Dbo->conditions($conditions);
2560
		$expected = " WHERE `User`.`first_name` = 'Firstname' AND `User`.`last_name` = 'Lastname'";
2561
		$this->assertEquals($expected, $result);
2562
 
2563
		$conditions = array(
2564
			'Thread.project_id' => 5,
2565
			'Thread.buyer_id' => 14,
2566
			'1=1 GROUP BY Thread.project_id'
2567
		);
2568
		$result = $this->Dbo->conditions($conditions);
2569
		$this->assertRegExp('/^\s*WHERE\s+`Thread`.`project_id`\s*=\s*5\s+AND\s+`Thread`.`buyer_id`\s*=\s*14\s+AND\s+1\s*=\s*1\s+GROUP BY `Thread`.`project_id`$/', $result);
2570
	}
2571
 
2572
/**
2573
 * testConditionsOptionalArguments method
2574
 *
2575
 * @return void
2576
 */
2577
	public function testConditionsOptionalArguments() {
2578
		$result = $this->Dbo->conditions(array('Member.name' => 'Mariano'), true, false);
2579
		$this->assertRegExp('/^\s*`Member`.`name`\s*=\s*\'Mariano\'\s*$/', $result);
2580
 
2581
		$result = $this->Dbo->conditions(array(), true, false);
2582
		$this->assertRegExp('/^\s*1\s*=\s*1\s*$/', $result);
2583
	}
2584
 
2585
/**
2586
 * testConditionsWithModel
2587
 *
2588
 * @return void
2589
 */
2590
	public function testConditionsWithModel() {
2591
		$this->Model = new Article2();
2592
 
2593
		$result = $this->Dbo->conditions(array('Article2.viewed >=' => 0), true, true, $this->Model);
2594
		$expected = " WHERE `Article2`.`viewed` >= 0";
2595
		$this->assertEquals($expected, $result);
2596
 
2597
		$result = $this->Dbo->conditions(array('Article2.viewed >=' => '0'), true, true, $this->Model);
2598
		$expected = " WHERE `Article2`.`viewed` >= 0";
2599
		$this->assertEquals($expected, $result);
2600
 
2601
		$result = $this->Dbo->conditions(array('Article2.viewed >=' => '1'), true, true, $this->Model);
2602
		$expected = " WHERE `Article2`.`viewed` >= 1";
2603
		$this->assertEquals($expected, $result);
2604
 
2605
		$result = $this->Dbo->conditions(array('Article2.rate_sum BETWEEN ? AND ?' => array(0, 10)), true, true, $this->Model);
2606
		$expected = " WHERE `Article2`.`rate_sum` BETWEEN 0 AND 10";
2607
		$this->assertEquals($expected, $result);
2608
 
2609
		$result = $this->Dbo->conditions(array('Article2.rate_sum BETWEEN ? AND ?' => array('0', '10')), true, true, $this->Model);
2610
		$expected = " WHERE `Article2`.`rate_sum` BETWEEN 0 AND 10";
2611
		$this->assertEquals($expected, $result);
2612
 
2613
		$result = $this->Dbo->conditions(array('Article2.rate_sum BETWEEN ? AND ?' => array('1', '10')), true, true, $this->Model);
2614
		$expected = " WHERE `Article2`.`rate_sum` BETWEEN 1 AND 10";
2615
		$this->assertEquals($expected, $result);
2616
	}
2617
 
2618
/**
2619
 * testFieldParsing method
2620
 *
2621
 * @return void
2622
 */
2623
	public function testFieldParsing() {
2624
		$this->Model = new TestModel();
2625
		$result = $this->Dbo->fields($this->Model, 'Vendor', "Vendor.id, COUNT(Model.vendor_id) AS `Vendor`.`count`");
2626
		$expected = array('`Vendor`.`id`', 'COUNT(`Model`.`vendor_id`) AS `Vendor`.`count`');
2627
		$this->assertEquals($expected, $result);
2628
 
2629
		$result = $this->Dbo->fields($this->Model, 'Vendor', "`Vendor`.`id`, COUNT(`Model`.`vendor_id`) AS `Vendor`.`count`");
2630
		$expected = array('`Vendor`.`id`', 'COUNT(`Model`.`vendor_id`) AS `Vendor`.`count`');
2631
		$this->assertEquals($expected, $result);
2632
 
2633
		$result = $this->Dbo->fields($this->Model, 'Post', "CONCAT(REPEAT(' ', COUNT(Parent.name) - 1), Node.name) AS name, Node.created");
2634
		$expected = array("CONCAT(REPEAT(' ', COUNT(`Parent`.`name`) - 1), Node.name) AS name", "`Node`.`created`");
2635
		$this->assertEquals($expected, $result);
2636
 
2637
		$result = $this->Dbo->fields($this->Model, null, 'round( (3.55441 * fooField), 3 ) AS test');
2638
		$this->assertEquals(array('round( (3.55441 * fooField), 3 ) AS test'), $result);
2639
 
2640
		$result = $this->Dbo->fields($this->Model, null, 'ROUND(`Rating`.`rate_total` / `Rating`.`rate_count`,2) AS rating');
2641
		$this->assertEquals(array('ROUND(`Rating`.`rate_total` / `Rating`.`rate_count`,2) AS rating'), $result);
2642
 
2643
		$result = $this->Dbo->fields($this->Model, null, 'ROUND(Rating.rate_total / Rating.rate_count,2) AS rating');
2644
		$this->assertEquals(array('ROUND(Rating.rate_total / Rating.rate_count,2) AS rating'), $result);
2645
 
2646
		$result = $this->Dbo->fields($this->Model, 'Post', "Node.created, CONCAT(REPEAT(' ', COUNT(Parent.name) - 1), Node.name) AS name");
2647
		$expected = array("`Node`.`created`", "CONCAT(REPEAT(' ', COUNT(`Parent`.`name`) - 1), Node.name) AS name");
2648
		$this->assertEquals($expected, $result);
2649
 
2650
		$result = $this->Dbo->fields($this->Model, 'Post', "2.2,COUNT(*), SUM(Something.else) as sum, Node.created, CONCAT(REPEAT(' ', COUNT(Parent.name) - 1), Node.name) AS name,Post.title,Post.1,1.1");
2651
		$expected = array(
2652
			'2.2', 'COUNT(*)', 'SUM(`Something`.`else`) as sum', '`Node`.`created`',
2653
			"CONCAT(REPEAT(' ', COUNT(`Parent`.`name`) - 1), Node.name) AS name", '`Post`.`title`', '`Post`.`1`', '1.1'
2654
		);
2655
		$this->assertEquals($expected, $result);
2656
 
2657
		$result = $this->Dbo->fields($this->Model, null, "(`Provider`.`star_total` / `Provider`.`total_ratings`) as `rating`");
2658
		$expected = array("(`Provider`.`star_total` / `Provider`.`total_ratings`) as `rating`");
2659
		$this->assertEquals($expected, $result);
2660
 
2661
		$result = $this->Dbo->fields($this->Model, 'Post');
2662
		$expected = array(
2663
			'`Post`.`id`', '`Post`.`client_id`', '`Post`.`name`', '`Post`.`login`',
2664
			'`Post`.`passwd`', '`Post`.`addr_1`', '`Post`.`addr_2`', '`Post`.`zip_code`',
2665
			'`Post`.`city`', '`Post`.`country`', '`Post`.`phone`', '`Post`.`fax`',
2666
			'`Post`.`url`', '`Post`.`email`', '`Post`.`comments`', '`Post`.`last_login`',
2667
			'`Post`.`created`', '`Post`.`updated`'
2668
		);
2669
		$this->assertEquals($expected, $result);
2670
 
2671
		$result = $this->Dbo->fields($this->Model, 'Other');
2672
		$expected = array(
2673
			'`Other`.`id`', '`Other`.`client_id`', '`Other`.`name`', '`Other`.`login`',
2674
			'`Other`.`passwd`', '`Other`.`addr_1`', '`Other`.`addr_2`', '`Other`.`zip_code`',
2675
			'`Other`.`city`', '`Other`.`country`', '`Other`.`phone`', '`Other`.`fax`',
2676
			'`Other`.`url`', '`Other`.`email`', '`Other`.`comments`', '`Other`.`last_login`',
2677
			'`Other`.`created`', '`Other`.`updated`'
2678
		);
2679
		$this->assertEquals($expected, $result);
2680
 
2681
		$result = $this->Dbo->fields($this->Model, null, array(), false);
2682
		$expected = array('id', 'client_id', 'name', 'login', 'passwd', 'addr_1', 'addr_2', 'zip_code', 'city', 'country', 'phone', 'fax', 'url', 'email', 'comments', 'last_login', 'created', 'updated');
2683
		$this->assertEquals($expected, $result);
2684
 
2685
		$result = $this->Dbo->fields($this->Model, null, 'COUNT(*)');
2686
		$expected = array('COUNT(*)');
2687
		$this->assertEquals($expected, $result);
2688
 
2689
		$result = $this->Dbo->fields($this->Model, null, 'SUM(Thread.unread_buyer) AS ' . $this->Dbo->name('sum_unread_buyer'));
2690
		$expected = array('SUM(`Thread`.`unread_buyer`) AS `sum_unread_buyer`');
2691
		$this->assertEquals($expected, $result);
2692
 
2693
		$result = $this->Dbo->fields($this->Model, null, 'name, count(*)');
2694
		$expected = array('`TestModel`.`name`', 'count(*)');
2695
		$this->assertEquals($expected, $result);
2696
 
2697
		$result = $this->Dbo->fields($this->Model, null, 'count(*), name');
2698
		$expected = array('count(*)', '`TestModel`.`name`');
2699
		$this->assertEquals($expected, $result);
2700
 
2701
		$result = $this->Dbo->fields(
2702
			$this->Model, null, 'field1, field2, field3, count(*), name'
2703
		);
2704
		$expected = array(
2705
			'`TestModel`.`field1`', '`TestModel`.`field2`',
2706
			'`TestModel`.`field3`', 'count(*)', '`TestModel`.`name`'
2707
		);
2708
		$this->assertEquals($expected, $result);
2709
 
2710
		$result = $this->Dbo->fields($this->Model, null, array('dayofyear(now())'));
2711
		$expected = array('dayofyear(now())');
2712
		$this->assertEquals($expected, $result);
2713
 
2714
		$result = $this->Dbo->fields($this->Model, null, array('MAX(Model.field) As Max'));
2715
		$expected = array('MAX(`Model`.`field`) As Max');
2716
		$this->assertEquals($expected, $result);
2717
 
2718
		$result = $this->Dbo->fields($this->Model, null, array('Model.field AS AnotherName'));
2719
		$expected = array('`Model`.`field` AS `AnotherName`');
2720
		$this->assertEquals($expected, $result);
2721
 
2722
		$result = $this->Dbo->fields($this->Model, null, array('field AS AnotherName'));
2723
		$expected = array('`field` AS `AnotherName`');
2724
		$this->assertEquals($expected, $result);
2725
 
2726
		$result = $this->Dbo->fields($this->Model, null, array(
2727
			'TestModel.field AS AnotherName'
2728
		));
2729
		$expected = array('`TestModel`.`field` AS `AnotherName`');
2730
		$this->assertEquals($expected, $result);
2731
 
2732
		$result = $this->Dbo->fields($this->Model, 'Foo', array(
2733
			'id', 'title', '(user_count + discussion_count + post_count) AS score'
2734
		));
2735
		$expected = array(
2736
			'`Foo`.`id`',
2737
			'`Foo`.`title`',
2738
			'(user_count + discussion_count + post_count) AS score'
2739
		);
2740
		$this->assertEquals($expected, $result);
2741
	}
2742
 
2743
/**
2744
 * test that fields() will accept objects made from DboSource::expression
2745
 *
2746
 * @return void
2747
 */
2748
	public function testFieldsWithExpression() {
2749
		$this->Model = new TestModel;
2750
		$expression = $this->Dbo->expression("CASE Sample.id WHEN 1 THEN 'Id One' ELSE 'Other Id' END AS case_col");
2751
		$result = $this->Dbo->fields($this->Model, null, array("id", $expression));
2752
		$expected = array(
2753
			'`TestModel`.`id`',
2754
			"CASE Sample.id WHEN 1 THEN 'Id One' ELSE 'Other Id' END AS case_col"
2755
		);
2756
		$this->assertEquals($expected, $result);
2757
	}
2758
 
2759
/**
2760
 * testRenderStatement method
2761
 *
2762
 * @return void
2763
 */
2764
	public function testRenderStatement() {
2765
		$result = $this->Dbo->renderStatement('select', array(
2766
			'fields' => 'id', 'table' => 'table', 'conditions' => 'WHERE 1=1',
2767
			'alias' => '', 'joins' => '', 'order' => '', 'limit' => '', 'group' => ''
2768
		));
2769
		$this->assertRegExp('/^\s*SELECT\s+id\s+FROM\s+table\s+WHERE\s+1=1\s*$/', $result);
2770
 
2771
		$result = $this->Dbo->renderStatement('update', array('fields' => 'value=2', 'table' => 'table', 'conditions' => 'WHERE 1=1', 'alias' => ''));
2772
		$this->assertRegExp('/^\s*UPDATE\s+table\s+SET\s+value=2\s+WHERE\s+1=1\s*$/', $result);
2773
 
2774
		$result = $this->Dbo->renderStatement('update', array('fields' => 'value=2', 'table' => 'table', 'conditions' => 'WHERE 1=1', 'alias' => 'alias', 'joins' => ''));
2775
		$this->assertRegExp('/^\s*UPDATE\s+table\s+AS\s+alias\s+SET\s+value=2\s+WHERE\s+1=1\s*$/', $result);
2776
 
2777
		$result = $this->Dbo->renderStatement('delete', array('fields' => 'value=2', 'table' => 'table', 'conditions' => 'WHERE 1=1', 'alias' => ''));
2778
		$this->assertRegExp('/^\s*DELETE\s+FROM\s+table\s+WHERE\s+1=1\s*$/', $result);
2779
 
2780
		$result = $this->Dbo->renderStatement('delete', array('fields' => 'value=2', 'table' => 'table', 'conditions' => 'WHERE 1=1', 'alias' => 'alias', 'joins' => ''));
2781
		$this->assertRegExp('/^\s*DELETE\s+alias\s+FROM\s+table\s+AS\s+alias\s+WHERE\s+1=1\s*$/', $result);
2782
	}
2783
 
2784
/**
2785
 * testSchema method
2786
 *
2787
 * @return void
2788
 */
2789
	public function testSchema() {
2790
		$Schema = new CakeSchema();
2791
		$Schema->tables = array('table' => array(), 'anotherTable' => array());
2792
 
2793
		$result = $this->Dbo->dropSchema($Schema, 'non_existing');
2794
		$this->assertTrue(empty($result));
2795
 
2796
		$result = $this->Dbo->dropSchema($Schema, 'table');
2797
		$this->assertRegExp('/^\s*DROP TABLE IF EXISTS\s+' . $this->Dbo->fullTableName('table') . ';\s*$/s', $result);
2798
	}
2799
 
2800
/**
2801
 * testDropSchemaNoSchema method
2802
 *
2803
 * @expectedException PHPUnit_Framework_Error
2804
 * @return void
2805
 */
2806
	public function testDropSchemaNoSchema() {
2807
		$this->Dbo->dropSchema(null);
2808
	}
2809
 
2810
/**
2811
 * testOrderParsing method
2812
 *
2813
 * @return void
2814
 */
2815
	public function testOrderParsing() {
2816
		$result = $this->Dbo->order("ADDTIME(Event.time_begin, '-06:00:00') ASC");
2817
		$expected = " ORDER BY ADDTIME(`Event`.`time_begin`, '-06:00:00') ASC";
2818
		$this->assertEquals($expected, $result);
2819
 
2820
		$result = $this->Dbo->order("title, id");
2821
		$this->assertRegExp('/^\s*ORDER BY\s+`title`\s+ASC,\s+`id`\s+ASC\s*$/', $result);
2822
 
2823
		$result = $this->Dbo->order("title desc, id desc");
2824
		$this->assertRegExp('/^\s*ORDER BY\s+`title`\s+desc,\s+`id`\s+desc\s*$/', $result);
2825
 
2826
		$result = $this->Dbo->order(array("title desc, id desc"));
2827
		$this->assertRegExp('/^\s*ORDER BY\s+`title`\s+desc,\s+`id`\s+desc\s*$/', $result);
2828
 
2829
		$result = $this->Dbo->order(array("title", "id"));
2830
		$this->assertRegExp('/^\s*ORDER BY\s+`title`\s+ASC,\s+`id`\s+ASC\s*$/', $result);
2831
 
2832
		$result = $this->Dbo->order(array(array('title'), array('id')));
2833
		$this->assertRegExp('/^\s*ORDER BY\s+`title`\s+ASC,\s+`id`\s+ASC\s*$/', $result);
2834
 
2835
		$result = $this->Dbo->order(array("Post.title" => 'asc', "Post.id" => 'desc'));
2836
		$this->assertRegExp('/^\s*ORDER BY\s+`Post`.`title`\s+asc,\s+`Post`.`id`\s+desc\s*$/', $result);
2837
 
2838
		$result = $this->Dbo->order(array(array("Post.title" => 'asc', "Post.id" => 'desc')));
2839
		$this->assertRegExp('/^\s*ORDER BY\s+`Post`.`title`\s+asc,\s+`Post`.`id`\s+desc\s*$/', $result);
2840
 
2841
		$result = $this->Dbo->order(array("title"));
2842
		$this->assertRegExp('/^\s*ORDER BY\s+`title`\s+ASC\s*$/', $result);
2843
 
2844
		$result = $this->Dbo->order(array(array("title")));
2845
		$this->assertRegExp('/^\s*ORDER BY\s+`title`\s+ASC\s*$/', $result);
2846
 
2847
		$result = $this->Dbo->order("Dealer.id = 7 desc, Dealer.id = 3 desc, Dealer.title asc");
2848
		$expected = " ORDER BY `Dealer`.`id` = 7 desc, `Dealer`.`id` = 3 desc, `Dealer`.`title` asc";
2849
		$this->assertEquals($expected, $result);
2850
 
2851
		$result = $this->Dbo->order(array("Page.name" => "='test' DESC"));
2852
		$this->assertRegExp("/^\s*ORDER BY\s+`Page`\.`name`\s*='test'\s+DESC\s*$/", $result);
2853
 
2854
		$result = $this->Dbo->order("Page.name = 'view' DESC");
2855
		$this->assertRegExp("/^\s*ORDER BY\s+`Page`\.`name`\s*=\s*'view'\s+DESC\s*$/", $result);
2856
 
2857
		$result = $this->Dbo->order("(Post.views)");
2858
		$this->assertRegExp("/^\s*ORDER BY\s+\(`Post`\.`views`\)\s+ASC\s*$/", $result);
2859
 
2860
		$result = $this->Dbo->order("(Post.views)*Post.views");
2861
		$this->assertRegExp("/^\s*ORDER BY\s+\(`Post`\.`views`\)\*`Post`\.`views`\s+ASC\s*$/", $result);
2862
 
2863
		$result = $this->Dbo->order("(Post.views) * Post.views");
2864
		$this->assertRegExp("/^\s*ORDER BY\s+\(`Post`\.`views`\) \* `Post`\.`views`\s+ASC\s*$/", $result);
2865
 
2866
		$result = $this->Dbo->order("(Model.field1 + Model.field2) * Model.field3");
2867
		$this->assertRegExp("/^\s*ORDER BY\s+\(`Model`\.`field1` \+ `Model`\.`field2`\) \* `Model`\.`field3`\s+ASC\s*$/", $result);
2868
 
2869
		$result = $this->Dbo->order("Model.name+0 ASC");
2870
		$this->assertRegExp("/^\s*ORDER BY\s+`Model`\.`name`\+0\s+ASC\s*$/", $result);
2871
 
2872
		$result = $this->Dbo->order("Anuncio.destaque & 2 DESC");
2873
		$expected = ' ORDER BY `Anuncio`.`destaque` & 2 DESC';
2874
		$this->assertEquals($expected, $result);
2875
 
2876
		$result = $this->Dbo->order("3963.191 * id");
2877
		$expected = ' ORDER BY 3963.191 * id ASC';
2878
		$this->assertEquals($expected, $result);
2879
 
2880
		$result = $this->Dbo->order(array('Property.sale_price IS NULL'));
2881
		$expected = ' ORDER BY `Property`.`sale_price` IS NULL ASC';
2882
		$this->assertEquals($expected, $result);
2883
	}
2884
 
2885
/**
2886
 * testComplexSortExpression method
2887
 *
2888
 * @return void
2889
 */
2890
	public function testComplexSortExpression() {
2891
		$result = $this->Dbo->order(array('(Model.field > 100) DESC', 'Model.field ASC'));
2892
		$this->assertRegExp("/^\s*ORDER BY\s+\(`Model`\.`field`\s+>\s+100\)\s+DESC,\s+`Model`\.`field`\s+ASC\s*$/", $result);
2893
	}
2894
 
2895
/**
2896
 * testCalculations method
2897
 *
2898
 * @return void
2899
 */
2900
	public function testCalculations() {
2901
		$this->Model = new TestModel();
2902
		$result = $this->Dbo->calculate($this->Model, 'count');
2903
		$this->assertEquals('COUNT(*) AS `count`', $result);
2904
 
2905
		$result = $this->Dbo->calculate($this->Model, 'count', array('id'));
2906
		$this->assertEquals('COUNT(`id`) AS `count`', $result);
2907
 
2908
		$result = $this->Dbo->calculate(
2909
			$this->Model,
2910
			'count',
2911
			array($this->Dbo->expression('DISTINCT id'))
2912
		);
2913
		$this->assertEquals('COUNT(DISTINCT id) AS `count`', $result);
2914
 
2915
		$result = $this->Dbo->calculate($this->Model, 'count', array('id', 'id_count'));
2916
		$this->assertEquals('COUNT(`id`) AS `id_count`', $result);
2917
 
2918
		$result = $this->Dbo->calculate($this->Model, 'count', array('Model.id', 'id_count'));
2919
		$this->assertEquals('COUNT(`Model`.`id`) AS `id_count`', $result);
2920
 
2921
		$result = $this->Dbo->calculate($this->Model, 'max', array('id'));
2922
		$this->assertEquals('MAX(`id`) AS `id`', $result);
2923
 
2924
		$result = $this->Dbo->calculate($this->Model, 'max', array('Model.id', 'id'));
2925
		$this->assertEquals('MAX(`Model`.`id`) AS `id`', $result);
2926
 
2927
		$result = $this->Dbo->calculate($this->Model, 'max', array('`Model`.`id`', 'id'));
2928
		$this->assertEquals('MAX(`Model`.`id`) AS `id`', $result);
2929
 
2930
		$result = $this->Dbo->calculate($this->Model, 'min', array('`Model`.`id`', 'id'));
2931
		$this->assertEquals('MIN(`Model`.`id`) AS `id`', $result);
2932
 
2933
		$result = $this->Dbo->calculate($this->Model, 'min', 'left');
2934
		$this->assertEquals('MIN(`left`) AS `left`', $result);
2935
	}
2936
 
2937
/**
2938
 * testLength method
2939
 *
2940
 * @return void
2941
 */
2942
	public function testLength() {
2943
		$result = $this->Dbo->length('varchar(255)');
2944
		$expected = 255;
2945
		$this->assertSame($expected, $result);
2946
 
2947
		$result = $this->Dbo->length('int(11)');
2948
		$expected = 11;
2949
		$this->assertSame($expected, $result);
2950
 
2951
		$result = $this->Dbo->length('float(5,3)');
2952
		$expected = '5,3';
2953
		$this->assertSame($expected, $result);
2954
 
2955
		$result = $this->Dbo->length('decimal(5,2)');
2956
		$expected = '5,2';
2957
		$this->assertSame($expected, $result);
2958
 
2959
		$result = $this->Dbo->length("enum('test','me','now')");
2960
		$expected = 4;
2961
		$this->assertSame($expected, $result);
2962
 
2963
		$result = $this->Dbo->length("set('a','b','cd')");
2964
		$expected = 2;
2965
		$this->assertSame($expected, $result);
2966
 
2967
		$result = $this->Dbo->length(false);
2968
		$this->assertTrue($result === null);
2969
 
2970
		$result = $this->Dbo->length('datetime');
2971
		$expected = null;
2972
		$this->assertSame($expected, $result);
2973
 
2974
		$result = $this->Dbo->length('text');
2975
		$expected = null;
2976
		$this->assertSame($expected, $result);
2977
	}
2978
 
2979
/**
2980
 * testBuildIndex method
2981
 *
2982
 * @return void
2983
 */
2984
	public function testBuildIndex() {
2985
		$data = array(
2986
			'PRIMARY' => array('column' => 'id')
2987
		);
2988
		$result = $this->Dbo->buildIndex($data);
2989
		$expected = array('PRIMARY KEY  (`id`)');
2990
		$this->assertSame($expected, $result);
2991
 
2992
		$data = array(
2993
			'MyIndex' => array('column' => 'id', 'unique' => true)
2994
		);
2995
		$result = $this->Dbo->buildIndex($data);
2996
		$expected = array('UNIQUE KEY `MyIndex` (`id`)');
2997
		$this->assertEquals($expected, $result);
2998
 
2999
		$data = array(
3000
			'MyIndex' => array('column' => array('id', 'name'), 'unique' => true)
3001
		);
3002
		$result = $this->Dbo->buildIndex($data);
3003
		$expected = array('UNIQUE KEY `MyIndex` (`id`, `name`)');
3004
		$this->assertEquals($expected, $result);
3005
 
3006
		$data = array(
3007
			'MyFtIndex' => array('column' => array('name', 'description'), 'type' => 'fulltext')
3008
		);
3009
		$result = $this->Dbo->buildIndex($data);
3010
		$expected = array('FULLTEXT KEY `MyFtIndex` (`name`, `description`)');
3011
		$this->assertEquals($expected, $result);
3012
 
3013
		$data = array(
3014
			'MyTextIndex' => array('column' => 'text_field', 'length' => array('text_field' => 20))
3015
		);
3016
		$result = $this->Dbo->buildIndex($data);
3017
		$expected = array('KEY `MyTextIndex` (`text_field`(20))');
3018
		$this->assertEquals($expected, $result);
3019
 
3020
		$data = array(
3021
			'MyMultiTextIndex' => array('column' => array('text_field1', 'text_field2'), 'length' => array('text_field1' => 20, 'text_field2' => 20))
3022
		);
3023
		$result = $this->Dbo->buildIndex($data);
3024
		$expected = array('KEY `MyMultiTextIndex` (`text_field1`(20), `text_field2`(20))');
3025
		$this->assertEquals($expected, $result);
3026
	}
3027
 
3028
/**
3029
 * testBuildColumn method
3030
 *
3031
 * @return void
3032
 */
3033
	public function testBuildColumn2() {
3034
		$data = array(
3035
			'name' => 'testName',
3036
			'type' => 'string',
3037
			'length' => 255,
3038
			'default',
3039
			'null' => true,
3040
			'key'
3041
		);
3042
		$result = $this->Dbo->buildColumn($data);
3043
		$expected = '`testName` varchar(255) DEFAULT NULL';
3044
		$this->assertEquals($expected, $result);
3045
 
3046
		$data = array(
3047
			'name' => 'int_field',
3048
			'type' => 'integer',
3049
			'default' => '',
3050
			'null' => false,
3051
		);
3052
		$restore = $this->Dbo->columns;
3053
 
3054
		$this->Dbo->columns = array('integer' => array('name' => 'int', 'limit' => '11', 'formatter' => 'intval'), );
3055
		$result = $this->Dbo->buildColumn($data);
3056
		$expected = '`int_field` int(11) NOT NULL';
3057
		$this->assertEquals($expected, $result);
3058
 
3059
		$this->Dbo->fieldParameters['param'] = array(
3060
			'value' => 'COLLATE',
3061
			'quote' => false,
3062
			'join' => ' ',
3063
			'column' => 'Collate',
3064
			'position' => 'beforeDefault',
3065
			'options' => array('GOOD', 'OK')
3066
		);
3067
		$data = array(
3068
			'name' => 'int_field',
3069
			'type' => 'integer',
3070
			'default' => '',
3071
			'null' => false,
3072
			'param' => 'BAD'
3073
		);
3074
		$result = $this->Dbo->buildColumn($data);
3075
		$expected = '`int_field` int(11) NOT NULL';
3076
		$this->assertEquals($expected, $result);
3077
 
3078
		$data = array(
3079
			'name' => 'int_field',
3080
			'type' => 'integer',
3081
			'default' => '',
3082
			'null' => false,
3083
			'param' => 'GOOD'
3084
		);
3085
		$result = $this->Dbo->buildColumn($data);
3086
		$expected = '`int_field` int(11) COLLATE GOOD NOT NULL';
3087
		$this->assertEquals($expected, $result);
3088
 
3089
		$this->Dbo->columns = $restore;
3090
 
3091
		$data = array(
3092
			'name' => 'created',
3093
			'type' => 'timestamp',
3094
			'default' => 'current_timestamp',
3095
			'null' => false,
3096
		);
3097
		$result = $this->Dbo->buildColumn($data);
3098
		$expected = '`created` timestamp DEFAULT CURRENT_TIMESTAMP NOT NULL';
3099
		$this->assertEquals($expected, $result);
3100
 
3101
		$data = array(
3102
			'name' => 'created',
3103
			'type' => 'timestamp',
3104
			'default' => 'CURRENT_TIMESTAMP',
3105
			'null' => true,
3106
		);
3107
		$result = $this->Dbo->buildColumn($data);
3108
		$expected = '`created` timestamp DEFAULT CURRENT_TIMESTAMP';
3109
		$this->assertEquals($expected, $result);
3110
 
3111
		$data = array(
3112
			'name' => 'modified',
3113
			'type' => 'timestamp',
3114
			'null' => true,
3115
		);
3116
		$result = $this->Dbo->buildColumn($data);
3117
		$expected = '`modified` timestamp NULL';
3118
		$this->assertEquals($expected, $result);
3119
 
3120
		$data = array(
3121
			'name' => 'modified',
3122
			'type' => 'timestamp',
3123
			'default' => null,
3124
			'null' => true,
3125
		);
3126
		$result = $this->Dbo->buildColumn($data);
3127
		$expected = '`modified` timestamp NULL';
3128
		$this->assertEquals($expected, $result);
3129
	}
3130
 
3131
/**
3132
 * testBuildColumnBadType method
3133
 *
3134
 * @expectedException PHPUnit_Framework_Error
3135
 * @return void
3136
 */
3137
	public function testBuildColumnBadType() {
3138
		$data = array(
3139
			'name' => 'testName',
3140
			'type' => 'varchar(255)',
3141
			'default',
3142
			'null' => true,
3143
			'key'
3144
		);
3145
		$this->Dbo->buildColumn($data);
3146
	}
3147
 
3148
/**
3149
 * test hasAny()
3150
 *
3151
 * @return void
3152
 */
3153
	public function testHasAny() {
3154
		$db = $this->Dbo->config['database'];
3155
		$this->Dbo = $this->getMock('Mysql', array('connect', '_execute', 'execute', 'value'));
3156
		$this->Dbo->config['database'] = $db;
3157
 
3158
		$this->Model = $this->getMock('TestModel', array('getDataSource'));
3159
		$this->Model->expects($this->any())
3160
			->method('getDataSource')
3161
			->will($this->returnValue($this->Dbo));
3162
 
3163
		$this->Dbo->expects($this->at(0))->method('value')
3164
			->with('harry')
3165
			->will($this->returnValue("'harry'"));
3166
 
3167
		$modelTable = $this->Dbo->fullTableName($this->Model);
3168
		$this->Dbo->expects($this->at(1))->method('execute')
3169
			->with('SELECT COUNT(`TestModel`.`id`) AS count FROM ' . $modelTable . ' AS `TestModel` WHERE `TestModel`.`name` = \'harry\'');
3170
		$this->Dbo->expects($this->at(2))->method('execute')
3171
			->with('SELECT COUNT(`TestModel`.`id`) AS count FROM ' . $modelTable . ' AS `TestModel` WHERE 1 = 1');
3172
 
3173
		$this->Dbo->hasAny($this->Model, array('TestModel.name' => 'harry'));
3174
		$this->Dbo->hasAny($this->Model, array());
3175
	}
3176
 
3177
/**
3178
 * test fields generating usable virtual fields to use in query
3179
 *
3180
 * @return void
3181
 */
3182
	public function testVirtualFields() {
3183
		$this->loadFixtures('Article', 'Comment', 'Tag');
3184
		$this->Dbo->virtualFieldSeparator = '__';
3185
		$Article = ClassRegistry::init('Article');
3186
		$commentsTable = $this->Dbo->fullTableName('comments', false, false);
3187
		$Article->virtualFields = array(
3188
			'this_moment' => 'NOW()',
3189
			'two' => '1 + 1',
3190
			'comment_count' => 'SELECT COUNT(*) FROM ' . $commentsTable .
3191
				' WHERE Article.id = ' . $commentsTable . '.article_id'
3192
		);
3193
		$result = $this->Dbo->fields($Article);
3194
		$expected = array(
3195
			'`Article`.`id`',
3196
			'`Article`.`user_id`',
3197
			'`Article`.`title`',
3198
			'`Article`.`body`',
3199
			'`Article`.`published`',
3200
			'`Article`.`created`',
3201
			'`Article`.`updated`',
3202
			'(NOW()) AS  `Article__this_moment`',
3203
			'(1 + 1) AS  `Article__two`',
3204
			"(SELECT COUNT(*) FROM $commentsTable WHERE `Article`.`id` = `$commentsTable`.`article_id`) AS  `Article__comment_count`"
3205
		);
3206
 
3207
		$this->assertEquals($expected, $result);
3208
 
3209
		$result = $this->Dbo->fields($Article, null, array('this_moment', 'title'));
3210
		$expected = array(
3211
			'`Article`.`title`',
3212
			'(NOW()) AS  `Article__this_moment`',
3213
		);
3214
		$this->assertEquals($expected, $result);
3215
 
3216
		$result = $this->Dbo->fields($Article, null, array('Article.title', 'Article.this_moment'));
3217
		$expected = array(
3218
			'`Article`.`title`',
3219
			'(NOW()) AS  `Article__this_moment`',
3220
		);
3221
		$this->assertEquals($expected, $result);
3222
 
3223
		$result = $this->Dbo->fields($Article, null, array('Article.this_moment', 'Article.title'));
3224
		$expected = array(
3225
			'`Article`.`title`',
3226
			'(NOW()) AS  `Article__this_moment`',
3227
		);
3228
		$this->assertEquals($expected, $result);
3229
 
3230
		$result = $this->Dbo->fields($Article, null, array('Article.*'));
3231
		$expected = array(
3232
			'`Article`.*',
3233
			'(NOW()) AS  `Article__this_moment`',
3234
			'(1 + 1) AS  `Article__two`',
3235
			"(SELECT COUNT(*) FROM $commentsTable WHERE `Article`.`id` = `$commentsTable`.`article_id`) AS  `Article__comment_count`"
3236
		);
3237
		$this->assertEquals($expected, $result);
3238
 
3239
		$result = $this->Dbo->fields($Article, null, array('*'));
3240
		$expected = array(
3241
			'*',
3242
			'(NOW()) AS  `Article__this_moment`',
3243
			'(1 + 1) AS  `Article__two`',
3244
			"(SELECT COUNT(*) FROM $commentsTable WHERE `Article`.`id` = `$commentsTable`.`article_id`) AS  `Article__comment_count`"
3245
		);
3246
		$this->assertEquals($expected, $result);
3247
	}
3248
 
3249
/**
3250
 * test conditions to generate query conditions for virtual fields
3251
 *
3252
 * @return void
3253
 */
3254
	public function testVirtualFieldsInConditions() {
3255
		$Article = ClassRegistry::init('Article');
3256
		$commentsTable = $this->Dbo->fullTableName('comments', false, false);
3257
 
3258
		$Article->virtualFields = array(
3259
			'this_moment' => 'NOW()',
3260
			'two' => '1 + 1',
3261
			'comment_count' => 'SELECT COUNT(*) FROM ' . $commentsTable .
3262
				' WHERE Article.id = ' . $commentsTable . '.article_id'
3263
		);
3264
		$conditions = array('two' => 2);
3265
		$result = $this->Dbo->conditions($conditions, true, false, $Article);
3266
		$expected = '(1 + 1) = 2';
3267
		$this->assertEquals($expected, $result);
3268
 
3269
		$conditions = array('this_moment BETWEEN ? AND ?' => array(1, 2));
3270
		$expected = 'NOW() BETWEEN 1 AND 2';
3271
		$result = $this->Dbo->conditions($conditions, true, false, $Article);
3272
		$this->assertEquals($expected, $result);
3273
 
3274
		$conditions = array('comment_count >' => 5);
3275
		$expected = "(SELECT COUNT(*) FROM $commentsTable WHERE `Article`.`id` = `$commentsTable`.`article_id`) > 5";
3276
		$result = $this->Dbo->conditions($conditions, true, false, $Article);
3277
		$this->assertEquals($expected, $result);
3278
 
3279
		$conditions = array('NOT' => array('two' => 2));
3280
		$result = $this->Dbo->conditions($conditions, true, false, $Article);
3281
		$expected = 'NOT ((1 + 1) = 2)';
3282
		$this->assertEquals($expected, $result);
3283
	}
3284
 
3285
/**
3286
 * test that virtualFields with complex functions and aliases work.
3287
 *
3288
 * @return void
3289
 */
3290
	public function testConditionsWithComplexVirtualFields() {
3291
		$Article = ClassRegistry::init('Article', 'Comment', 'Tag');
3292
		$Article->virtualFields = array(
3293
			'distance' => 'ACOS(SIN(20 * PI() / 180)
3294
					* SIN(Article.latitude * PI() / 180)
3295
					+ COS(20 * PI() / 180)
3296
					* COS(Article.latitude * PI() / 180)
3297
					* COS((50 - Article.longitude) * PI() / 180)
3298
				) * 180 / PI() * 60 * 1.1515 * 1.609344'
3299
		);
3300
		$conditions = array('distance >=' => 20);
3301
		$result = $this->Dbo->conditions($conditions, true, true, $Article);
3302
 
3303
		$this->assertRegExp('/\) >= 20/', $result);
3304
		$this->assertRegExp('/[`\'"]Article[`\'"].[`\'"]latitude[`\'"]/', $result);
3305
		$this->assertRegExp('/[`\'"]Article[`\'"].[`\'"]longitude[`\'"]/', $result);
3306
	}
3307
 
3308
/**
3309
 * test calculate to generate claculate statements on virtual fields
3310
 *
3311
 * @return void
3312
 */
3313
	public function testVirtualFieldsInCalculate() {
3314
		$Article = ClassRegistry::init('Article');
3315
		$commentsTable = $this->Dbo->fullTableName('comments', false, false);
3316
		$Article->virtualFields = array(
3317
			'this_moment' => 'NOW()',
3318
			'two' => '1 + 1',
3319
			'comment_count' => 'SELECT COUNT(*) FROM ' . $commentsTable .
3320
				' WHERE Article.id = ' . $commentsTable . '.article_id'
3321
		);
3322
 
3323
		$result = $this->Dbo->calculate($Article, 'count', array('this_moment'));
3324
		$expected = 'COUNT(NOW()) AS `count`';
3325
		$this->assertEquals($expected, $result);
3326
 
3327
		$result = $this->Dbo->calculate($Article, 'max', array('comment_count'));
3328
		$expected = "MAX(SELECT COUNT(*) FROM $commentsTable WHERE `Article`.`id` = `$commentsTable`.`article_id`) AS `comment_count`";
3329
		$this->assertEquals($expected, $result);
3330
	}
3331
 
3332
/**
3333
 * test reading virtual fields containing newlines when recursive > 0
3334
 *
3335
 * @return void
3336
 */
3337
	public function testReadVirtualFieldsWithNewLines() {
3338
		$Article = new Article();
3339
		$Article->recursive = 1;
3340
		$Article->virtualFields = array(
3341
			'test' => '
3342
			User.id + User.id
3343
			'
3344
		);
3345
		$result = $this->Dbo->fields($Article, null, array());
3346
		$result = $this->Dbo->fields($Article, $Article->alias, $result);
3347
		$this->assertRegExp('/[`\"]User[`\"]\.[`\"]id[`\"] \+ [`\"]User[`\"]\.[`\"]id[`\"]/', $result[7]);
3348
	}
3349
 
3350
/**
3351
 * test group to generate GROUP BY statements on virtual fields
3352
 *
3353
 * @return void
3354
 */
3355
	public function testVirtualFieldsInGroup() {
3356
		$Article = ClassRegistry::init('Article');
3357
		$Article->virtualFields = array(
3358
			'this_year' => 'YEAR(Article.created)'
3359
		);
3360
 
3361
		$result = $this->Dbo->group('this_year', $Article);
3362
 
3363
		$expected = " GROUP BY (YEAR(`Article`.`created`))";
3364
		$this->assertEquals($expected, $result);
3365
	}
3366
 
3367
/**
3368
 * test that virtualFields with complex functions and aliases work.
3369
 *
3370
 * @return void
3371
 */
3372
	public function testFieldsWithComplexVirtualFields() {
3373
		$Article = new Article();
3374
		$Article->virtualFields = array(
3375
			'distance' => 'ACOS(SIN(20 * PI() / 180)
3376
					* SIN(Article.latitude * PI() / 180)
3377
					+ COS(20 * PI() / 180)
3378
					* COS(Article.latitude * PI() / 180)
3379
					* COS((50 - Article.longitude) * PI() / 180)
3380
				) * 180 / PI() * 60 * 1.1515 * 1.609344'
3381
		);
3382
 
3383
		$fields = array('id', 'distance');
3384
		$result = $this->Dbo->fields($Article, null, $fields);
3385
		$qs = $this->Dbo->startQuote;
3386
		$qe = $this->Dbo->endQuote;
3387
 
3388
		$this->assertEquals("{$qs}Article{$qe}.{$qs}id{$qe}", $result[0]);
3389
		$this->assertRegExp('/Article__distance/', $result[1]);
3390
		$this->assertRegExp('/[`\'"]Article[`\'"].[`\'"]latitude[`\'"]/', $result[1]);
3391
		$this->assertRegExp('/[`\'"]Article[`\'"].[`\'"]longitude[`\'"]/', $result[1]);
3392
	}
3393
 
3394
/**
3395
 * test that execute runs queries.
3396
 *
3397
 * @return void
3398
 */
3399
	public function testExecute() {
3400
		$query = 'SELECT * FROM ' . $this->Dbo->fullTableName('articles') . ' WHERE 1 = 1';
3401
		$this->Dbo->took = null;
3402
		$this->Dbo->affected = null;
3403
		$result = $this->Dbo->execute($query, array('log' => false));
3404
		$this->assertNotNull($result, 'No query performed! %s');
3405
		$this->assertNull($this->Dbo->took, 'Stats were set %s');
3406
		$this->assertNull($this->Dbo->affected, 'Stats were set %s');
3407
 
3408
		$result = $this->Dbo->execute($query);
3409
		$this->assertNotNull($result, 'No query performed! %s');
3410
		$this->assertNotNull($this->Dbo->took, 'Stats were not set %s');
3411
		$this->assertNotNull($this->Dbo->affected, 'Stats were not set %s');
3412
	}
3413
 
3414
/**
3415
 * test a full example of using virtual fields
3416
 *
3417
 * @return void
3418
 */
3419
	public function testVirtualFieldsFetch() {
3420
		$this->loadFixtures('Article', 'Comment');
3421
 
3422
		$Article = ClassRegistry::init('Article');
3423
		$Article->virtualFields = array(
3424
			'comment_count' => 'SELECT COUNT(*) FROM ' . $this->Dbo->fullTableName('comments') .
3425
				' WHERE Article.id = ' . $this->Dbo->fullTableName('comments') . '.article_id'
3426
		);
3427
 
3428
		$conditions = array('comment_count >' => 2);
3429
		$query = 'SELECT ' . implode(',', $this->Dbo->fields($Article, null, array('id', 'comment_count'))) .
3430
				' FROM ' . $this->Dbo->fullTableName($Article) . ' Article ' . $this->Dbo->conditions($conditions, true, true, $Article);
3431
		$result = $this->Dbo->fetchAll($query);
3432
		$expected = array(array(
3433
			'Article' => array('id' => 1, 'comment_count' => 4)
3434
		));
3435
		$this->assertEquals($expected, $result);
3436
	}
3437
 
3438
/**
3439
 * test reading complex virtualFields with subqueries.
3440
 *
3441
 * @return void
3442
 */
3443
	public function testVirtualFieldsComplexRead() {
3444
		$this->loadFixtures('DataTest', 'Article', 'Comment', 'User', 'Tag', 'ArticlesTag');
3445
 
3446
		$Article = ClassRegistry::init('Article');
3447
		$commentTable = $this->Dbo->fullTableName('comments');
3448
		$Article = ClassRegistry::init('Article');
3449
		$Article->virtualFields = array(
3450
			'comment_count' => 'SELECT COUNT(*) FROM ' . $commentTable .
3451
				' AS Comment WHERE Article.id = Comment.article_id'
3452
		);
3453
		$result = $Article->find('all');
3454
		$this->assertTrue(count($result) > 0);
3455
		$this->assertTrue($result[0]['Article']['comment_count'] > 0);
3456
 
3457
		$DataTest = ClassRegistry::init('DataTest');
3458
		$DataTest->virtualFields = array(
3459
			'complicated' => 'ACOS(SIN(20 * PI() / 180)
3460
				* SIN(DataTest.float * PI() / 180)
3461
				+ COS(20 * PI() / 180)
3462
				* COS(DataTest.count * PI() / 180)
3463
				* COS((50 - DataTest.float) * PI() / 180)
3464
				) * 180 / PI() * 60 * 1.1515 * 1.609344'
3465
		);
3466
		$result = $DataTest->find('all');
3467
		$this->assertTrue(count($result) > 0);
3468
		$this->assertTrue($result[0]['DataTest']['complicated'] > 0);
3469
	}
3470
 
3471
/**
3472
 * testIntrospectType method
3473
 *
3474
 * @return void
3475
 */
3476
	public function testIntrospectType() {
3477
		$this->assertEquals('integer', $this->Dbo->introspectType(0));
3478
		$this->assertEquals('integer', $this->Dbo->introspectType(2));
3479
		$this->assertEquals('string', $this->Dbo->introspectType('2'));
3480
		$this->assertEquals('string', $this->Dbo->introspectType('2.2'));
3481
		$this->assertEquals('float', $this->Dbo->introspectType(2.2));
3482
		$this->assertEquals('string', $this->Dbo->introspectType('stringme'));
3483
		$this->assertEquals('string', $this->Dbo->introspectType('0stringme'));
3484
 
3485
		$data = array(2.2);
3486
		$this->assertEquals('float', $this->Dbo->introspectType($data));
3487
 
3488
		$data = array('2.2');
3489
		$this->assertEquals('float', $this->Dbo->introspectType($data));
3490
 
3491
		$data = array(2);
3492
		$this->assertEquals('integer', $this->Dbo->introspectType($data));
3493
 
3494
		$data = array('2');
3495
		$this->assertEquals('integer', $this->Dbo->introspectType($data));
3496
 
3497
		$data = array('string');
3498
		$this->assertEquals('string', $this->Dbo->introspectType($data));
3499
 
3500
		$data = array(2.2, '2.2');
3501
		$this->assertEquals('float', $this->Dbo->introspectType($data));
3502
 
3503
		$data = array(2, '2');
3504
		$this->assertEquals('integer', $this->Dbo->introspectType($data));
3505
 
3506
		$data = array('string one', 'string two');
3507
		$this->assertEquals('string', $this->Dbo->introspectType($data));
3508
 
3509
		$data = array('2.2', 3);
3510
		$this->assertEquals('integer', $this->Dbo->introspectType($data));
3511
 
3512
		$data = array('2.2', '0stringme');
3513
		$this->assertEquals('string', $this->Dbo->introspectType($data));
3514
 
3515
		$data = array(2.2, 3);
3516
		$this->assertEquals('integer', $this->Dbo->introspectType($data));
3517
 
3518
		$data = array(2.2, '0stringme');
3519
		$this->assertEquals('string', $this->Dbo->introspectType($data));
3520
 
3521
		$data = array(2, 'stringme');
3522
		$this->assertEquals('string', $this->Dbo->introspectType($data));
3523
 
3524
		$data = array(2, '2.2', 'stringgme');
3525
		$this->assertEquals('string', $this->Dbo->introspectType($data));
3526
 
3527
		$data = array(2, '2.2');
3528
		$this->assertEquals('integer', $this->Dbo->introspectType($data));
3529
 
3530
		$data = array(2, 2.2);
3531
		$this->assertEquals('integer', $this->Dbo->introspectType($data));
3532
 
3533
		// null
3534
		$result = $this->Dbo->value(null, 'boolean');
3535
		$this->assertEquals('NULL', $result);
3536
 
3537
		// EMPTY STRING
3538
		$result = $this->Dbo->value('', 'boolean');
3539
		$this->assertEquals("'0'", $result);
3540
 
3541
		// BOOLEAN
3542
		$result = $this->Dbo->value('true', 'boolean');
3543
		$this->assertEquals("'1'", $result);
3544
 
3545
		$result = $this->Dbo->value('false', 'boolean');
3546
		$this->assertEquals("'1'", $result);
3547
 
3548
		$result = $this->Dbo->value(true, 'boolean');
3549
		$this->assertEquals("'1'", $result);
3550
 
3551
		$result = $this->Dbo->value(false, 'boolean');
3552
		$this->assertEquals("'0'", $result);
3553
 
3554
		$result = $this->Dbo->value(1, 'boolean');
3555
		$this->assertEquals("'1'", $result);
3556
 
3557
		$result = $this->Dbo->value(0, 'boolean');
3558
		$this->assertEquals("'0'", $result);
3559
 
3560
		$result = $this->Dbo->value('abc', 'boolean');
3561
		$this->assertEquals("'1'", $result);
3562
 
3563
		$result = $this->Dbo->value(1.234, 'boolean');
3564
		$this->assertEquals("'1'", $result);
3565
 
3566
		$result = $this->Dbo->value('1.234e05', 'boolean');
3567
		$this->assertEquals("'1'", $result);
3568
 
3569
		// NUMBERS
3570
		$result = $this->Dbo->value(123, 'integer');
3571
		$this->assertEquals(123, $result);
3572
 
3573
		$result = $this->Dbo->value('123', 'integer');
3574
		$this->assertEquals('123', $result);
3575
 
3576
		$result = $this->Dbo->value('0123', 'integer');
3577
		$this->assertEquals("'0123'", $result);
3578
 
3579
		$result = $this->Dbo->value('0x123ABC', 'integer');
3580
		$this->assertEquals("'0x123ABC'", $result);
3581
 
3582
		$result = $this->Dbo->value('0x123', 'integer');
3583
		$this->assertEquals("'0x123'", $result);
3584
 
3585
		$result = $this->Dbo->value(1.234, 'float');
3586
		$this->assertEquals(1.234, $result);
3587
 
3588
		$result = $this->Dbo->value('1.234', 'float');
3589
		$this->assertEquals('1.234', $result);
3590
 
3591
		$result = $this->Dbo->value(' 1.234 ', 'float');
3592
		$this->assertEquals("' 1.234 '", $result);
3593
 
3594
		$result = $this->Dbo->value('1.234e05', 'float');
3595
		$this->assertEquals("'1.234e05'", $result);
3596
 
3597
		$result = $this->Dbo->value('1.234e+5', 'float');
3598
		$this->assertEquals("'1.234e+5'", $result);
3599
 
3600
		$result = $this->Dbo->value('1,234', 'float');
3601
		$this->assertEquals("'1,234'", $result);
3602
 
3603
		$result = $this->Dbo->value('FFF', 'integer');
3604
		$this->assertEquals("'FFF'", $result);
3605
 
3606
		$result = $this->Dbo->value('abc', 'integer');
3607
		$this->assertEquals("'abc'", $result);
3608
 
3609
		// STRINGS
3610
		$result = $this->Dbo->value('123', 'string');
3611
		$this->assertEquals("'123'", $result);
3612
 
3613
		$result = $this->Dbo->value(123, 'string');
3614
		$this->assertEquals("'123'", $result);
3615
 
3616
		$result = $this->Dbo->value(1.234, 'string');
3617
		$this->assertEquals("'1.234'", $result);
3618
 
3619
		$result = $this->Dbo->value('abc', 'string');
3620
		$this->assertEquals("'abc'", $result);
3621
 
3622
		$result = $this->Dbo->value(' abc ', 'string');
3623
		$this->assertEquals("' abc '", $result);
3624
 
3625
		$result = $this->Dbo->value('a bc', 'string');
3626
		$this->assertEquals("'a bc'", $result);
3627
	}
3628
 
3629
/**
3630
 * testRealQueries method
3631
 *
3632
 * @return void
3633
 */
3634
	public function testRealQueries() {
3635
		$this->loadFixtures('Apple', 'Article', 'User', 'Comment', 'Tag', 'Sample', 'ArticlesTag');
3636
 
3637
		$Apple = ClassRegistry::init('Apple');
3638
		$Article = ClassRegistry::init('Article');
3639
 
3640
		$result = $this->Dbo->rawQuery('SELECT color, name FROM ' . $this->Dbo->fullTableName('apples'));
3641
		$this->assertTrue(!empty($result));
3642
 
3643
		$result = $this->Dbo->fetchRow($result);
3644
		$expected = array($this->Dbo->fullTableName('apples', false, false) => array(
3645
			'color' => 'Red 1',
3646
			'name' => 'Red Apple 1'
3647
		));
3648
		$this->assertEquals($expected, $result);
3649
 
3650
		$result = $this->Dbo->fetchAll('SELECT name FROM ' . $this->Dbo->fullTableName('apples') . ' ORDER BY id');
3651
		$expected = array(
3652
			array($this->Dbo->fullTableName('apples', false, false) => array('name' => 'Red Apple 1')),
3653
			array($this->Dbo->fullTableName('apples', false, false) => array('name' => 'Bright Red Apple')),
3654
			array($this->Dbo->fullTableName('apples', false, false) => array('name' => 'green blue')),
3655
			array($this->Dbo->fullTableName('apples', false, false) => array('name' => 'Test Name')),
3656
			array($this->Dbo->fullTableName('apples', false, false) => array('name' => 'Blue Green')),
3657
			array($this->Dbo->fullTableName('apples', false, false) => array('name' => 'My new apple')),
3658
			array($this->Dbo->fullTableName('apples', false, false) => array('name' => 'Some odd color'))
3659
		);
3660
		$this->assertEquals($expected, $result);
3661
 
3662
		$result = $this->Dbo->field($this->Dbo->fullTableName('apples', false, false), 'SELECT color, name FROM ' . $this->Dbo->fullTableName('apples') . ' ORDER BY id');
3663
		$expected = array(
3664
			'color' => 'Red 1',
3665
			'name' => 'Red Apple 1'
3666
		);
3667
		$this->assertEquals($expected, $result);
3668
 
3669
		$Apple->unbindModel(array(), false);
3670
		$result = $this->Dbo->read($Apple, array(
3671
			'fields' => array($Apple->escapeField('name')),
3672
			'conditions' => null,
3673
			'recursive' => -1
3674
		));
3675
		$expected = array(
3676
			array('Apple' => array('name' => 'Red Apple 1')),
3677
			array('Apple' => array('name' => 'Bright Red Apple')),
3678
			array('Apple' => array('name' => 'green blue')),
3679
			array('Apple' => array('name' => 'Test Name')),
3680
			array('Apple' => array('name' => 'Blue Green')),
3681
			array('Apple' => array('name' => 'My new apple')),
3682
			array('Apple' => array('name' => 'Some odd color'))
3683
		);
3684
		$this->assertEquals($expected, $result);
3685
 
3686
		$result = $this->Dbo->read($Article, array(
3687
			'fields' => array('id', 'user_id', 'title'),
3688
			'conditions' => null,
3689
			'recursive' => 1
3690
		));
3691
 
3692
		$this->assertTrue(Set::matches('/Article[id=1]', $result));
3693
		$this->assertTrue(Set::matches('/Comment[id=1]', $result));
3694
		$this->assertTrue(Set::matches('/Comment[id=2]', $result));
3695
		$this->assertFalse(Set::matches('/Comment[id=10]', $result));
3696
	}
3697
 
3698
/**
3699
 * @expectedException MissingConnectionException
3700
 * @return void
3701
 */
3702
	public function testExceptionOnBrokenConnection() {
3703
		new Mysql(array(
3704
			'driver' => 'mysql',
3705
			'host' => 'imaginary_host',
3706
			'login' => 'mark',
3707
			'password' => 'inyurdatabase',
3708
			'database' => 'imaginary'
3709
		));
3710
	}
3711
 
3712
/**
3713
 * testStatements method
3714
 *
3715
 * @return void
3716
 */
3717
	public function testUpdateStatements() {
3718
		$this->loadFixtures('Article', 'User');
3719
		$test = ConnectionManager::getDatasource('test');
3720
		$db = $test->config['database'];
3721
 
3722
		$this->Dbo = $this->getMock('Mysql', array('execute'), array($test->config));
3723
 
3724
		$this->Dbo->expects($this->at(0))->method('execute')
3725
			->with("UPDATE `$db`.`articles` SET `field1` = 'value1'  WHERE 1 = 1");
3726
 
3727
		$this->Dbo->expects($this->at(1))->method('execute')
3728
			->with("UPDATE `$db`.`articles` AS `Article` LEFT JOIN `$db`.`users` AS `User` ON " .
3729
				"(`Article`.`user_id` = `User`.`id`)" .
3730
				" SET `Article`.`field1` = 2  WHERE 2=2");
3731
 
3732
		$this->Dbo->expects($this->at(2))->method('execute')
3733
			->with("UPDATE `$db`.`articles` AS `Article` LEFT JOIN `$db`.`users` AS `User` ON " .
3734
				"(`Article`.`user_id` = `User`.`id`)" .
3735
				" SET `Article`.`field1` = 'value'  WHERE `index` = 'val'");
3736
 
3737
		$Article = new Article();
3738
 
3739
		$this->Dbo->update($Article, array('field1'), array('value1'));
3740
		$this->Dbo->update($Article, array('field1'), array('2'), '2=2');
3741
		$this->Dbo->update($Article, array('field1'), array("'value'"), array('index' => 'val'));
3742
	}
3743
 
3744
/**
3745
 * Test deletes with a mock.
3746
 *
3747
 * @return void
3748
 */
3749
	public function testDeleteStatements() {
3750
		$this->loadFixtures('Article', 'User');
3751
		$test = ConnectionManager::getDatasource('test');
3752
		$db = $test->config['database'];
3753
 
3754
		$this->Dbo = $this->getMock('Mysql', array('execute'), array($test->config));
3755
 
3756
		$this->Dbo->expects($this->at(0))->method('execute')
3757
			->with("DELETE  FROM `$db`.`articles`  WHERE 1 = 1");
3758
 
3759
		$this->Dbo->expects($this->at(1))->method('execute')
3760
			->with("DELETE `Article` FROM `$db`.`articles` AS `Article` LEFT JOIN `$db`.`users` AS `User` " .
3761
				"ON (`Article`.`user_id` = `User`.`id`)" .
3762
				"  WHERE 1 = 1");
3763
 
3764
		$this->Dbo->expects($this->at(2))->method('execute')
3765
			->with("DELETE `Article` FROM `$db`.`articles` AS `Article` LEFT JOIN `$db`.`users` AS `User` " .
3766
				"ON (`Article`.`user_id` = `User`.`id`)" .
3767
				"  WHERE 2=2");
3768
		$Article = new Article();
3769
 
3770
		$this->Dbo->delete($Article);
3771
		$this->Dbo->delete($Article, true);
3772
		$this->Dbo->delete($Article, '2=2');
3773
	}
3774
 
3775
/**
3776
 * Test truncate with a mock.
3777
 *
3778
 * @return void
3779
 */
3780
	public function testTruncateStatements() {
3781
		$this->loadFixtures('Article', 'User');
3782
		$db = ConnectionManager::getDatasource('test');
3783
		$schema = $db->config['database'];
3784
		$Article = new Article();
3785
 
3786
		$this->Dbo = $this->getMock('Mysql', array('execute'), array($db->config));
3787
 
3788
		$this->Dbo->expects($this->at(0))->method('execute')
3789
			->with("TRUNCATE TABLE `$schema`.`articles`");
3790
		$this->Dbo->truncate($Article);
3791
 
3792
		$this->Dbo->expects($this->at(0))->method('execute')
3793
			->with("TRUNCATE TABLE `$schema`.`articles`");
3794
		$this->Dbo->truncate('articles');
3795
 
3796
		// #2355: prevent duplicate prefix
3797
		$this->Dbo->config['prefix'] = 'tbl_';
3798
		$Article->tablePrefix = 'tbl_';
3799
		$this->Dbo->expects($this->at(0))->method('execute')
3800
			->with("TRUNCATE TABLE `$schema`.`tbl_articles`");
3801
		$this->Dbo->truncate($Article);
3802
 
3803
		$this->Dbo->expects($this->at(0))->method('execute')
3804
			->with("TRUNCATE TABLE `$schema`.`tbl_articles`");
3805
		$this->Dbo->truncate('articles');
3806
	}
3807
 
3808
/**
3809
 * Test nested transaction
3810
 *
3811
 * @return void
3812
 */
3813
	public function testNestedTransaction() {
3814
		$nested = $this->Dbo->useNestedTransactions;
3815
		$this->Dbo->useNestedTransactions = true;
3816
		if ($this->Dbo->nestedTransactionSupported() === false) {
3817
			$this->Dbo->useNestedTransactions = $nested;
3818
			$this->skipIf(true, 'The MySQL server do not support nested transaction');
3819
		}
3820
 
3821
		$this->loadFixtures('Inno');
3822
		$model = ClassRegistry::init('Inno');
3823
		$model->hasOne = $model->hasMany = $model->belongsTo = $model->hasAndBelongsToMany = array();
3824
		$model->cacheQueries = false;
3825
		$this->Dbo->cacheMethods = false;
3826
 
3827
		$this->assertTrue($this->Dbo->begin());
3828
		$this->assertNotEmpty($model->read(null, 1));
3829
 
3830
		$this->assertTrue($this->Dbo->begin());
3831
		$this->assertTrue($model->delete(1));
3832
		$this->assertEmpty($model->read(null, 1));
3833
		$this->assertTrue($this->Dbo->rollback());
3834
		$this->assertNotEmpty($model->read(null, 1));
3835
 
3836
		$this->assertTrue($this->Dbo->begin());
3837
		$this->assertTrue($model->delete(1));
3838
		$this->assertEmpty($model->read(null, 1));
3839
		$this->assertTrue($this->Dbo->commit());
3840
		$this->assertEmpty($model->read(null, 1));
3841
 
3842
		$this->assertTrue($this->Dbo->rollback());
3843
		$this->assertNotEmpty($model->read(null, 1));
3844
 
3845
		$this->Dbo->useNestedTransactions = $nested;
3846
	}
3847
 
3848
}