PageRenderTime 67ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/Cake/Test/Case/Model/Datasource/Database/MysqlTest.php

https://bitbucket.org/udeshika/fake_twitter
PHP | 3522 lines | 2628 code | 515 blank | 379 comment | 15 complexity | 8913167100f9ae216fe14e4cc1b7235c MD5 | raw file
  1. <?php
  2. /**
  3. * DboMysqlTest file
  4. *
  5. * PHP 5
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
  9. *
  10. * Licensed under The MIT License
  11. * Redistributions of files must retain the above copyright notice.
  12. *
  13. * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
  14. * @link http://cakephp.org CakePHP(tm) Project
  15. * @package Cake.Test.Case.Model.Datasource.Database
  16. * @since CakePHP(tm) v 1.2.0
  17. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  18. */
  19. App::uses('Model', 'Model');
  20. App::uses('AppModel', 'Model');
  21. App::uses('Mysql', 'Model/Datasource/Database');
  22. App::uses('CakeSchema', 'Model');
  23. require_once dirname(dirname(dirname(__FILE__))) . DS . 'models.php';
  24. /**
  25. * DboMysqlTest class
  26. *
  27. * @package Cake.Test.Case.Model.Datasource.Database
  28. */
  29. class MysqlTest extends CakeTestCase {
  30. /**
  31. * autoFixtures property
  32. *
  33. * @var bool false
  34. */
  35. public $autoFixtures = false;
  36. /**
  37. * fixtures property
  38. *
  39. * @var array
  40. */
  41. public $fixtures = array(
  42. 'core.apple', 'core.article', 'core.articles_tag', 'core.attachment', 'core.comment',
  43. 'core.sample', 'core.tag', 'core.user', 'core.post', 'core.author', 'core.data_test',
  44. 'core.binary_test'
  45. );
  46. /**
  47. * The Dbo instance to be tested
  48. *
  49. * @var DboSource
  50. */
  51. public $Dbo = null;
  52. /**
  53. * Sets up a Dbo class instance for testing
  54. *
  55. */
  56. public function setUp() {
  57. $this->Dbo = ConnectionManager::getDataSource('test');
  58. if (!($this->Dbo instanceof Mysql)) {
  59. $this->markTestSkipped('The MySQL extension is not available.');
  60. }
  61. $this->_debug = Configure::read('debug');
  62. Configure::write('debug', 1);
  63. $this->model = ClassRegistry::init('MysqlTestModel');
  64. }
  65. /**
  66. * Sets up a Dbo class instance for testing
  67. *
  68. */
  69. public function tearDown() {
  70. unset($this->model);
  71. ClassRegistry::flush();
  72. Configure::write('debug', $this->_debug);
  73. }
  74. /**
  75. * Test Dbo value method
  76. *
  77. * @group quoting
  78. */
  79. public function testQuoting() {
  80. $result = $this->Dbo->fields($this->model);
  81. $expected = array(
  82. '`MysqlTestModel`.`id`',
  83. '`MysqlTestModel`.`client_id`',
  84. '`MysqlTestModel`.`name`',
  85. '`MysqlTestModel`.`login`',
  86. '`MysqlTestModel`.`passwd`',
  87. '`MysqlTestModel`.`addr_1`',
  88. '`MysqlTestModel`.`addr_2`',
  89. '`MysqlTestModel`.`zip_code`',
  90. '`MysqlTestModel`.`city`',
  91. '`MysqlTestModel`.`country`',
  92. '`MysqlTestModel`.`phone`',
  93. '`MysqlTestModel`.`fax`',
  94. '`MysqlTestModel`.`url`',
  95. '`MysqlTestModel`.`email`',
  96. '`MysqlTestModel`.`comments`',
  97. '`MysqlTestModel`.`last_login`',
  98. '`MysqlTestModel`.`created`',
  99. '`MysqlTestModel`.`updated`'
  100. );
  101. $this->assertEquals($expected, $result);
  102. $expected = 1.2;
  103. $result = $this->Dbo->value(1.2, 'float');
  104. $this->assertEquals($expected, $result);
  105. $expected = "'1,2'";
  106. $result = $this->Dbo->value('1,2', 'float');
  107. $this->assertEquals($expected, $result);
  108. $expected = "'4713e29446'";
  109. $result = $this->Dbo->value('4713e29446');
  110. $this->assertEquals($expected, $result);
  111. $expected = 'NULL';
  112. $result = $this->Dbo->value('', 'integer');
  113. $this->assertEquals($expected, $result);
  114. $expected = "'0'";
  115. $result = $this->Dbo->value('', 'boolean');
  116. $this->assertEquals($expected, $result);
  117. $expected = 10010001;
  118. $result = $this->Dbo->value(10010001);
  119. $this->assertEquals($expected, $result);
  120. $expected = "'00010010001'";
  121. $result = $this->Dbo->value('00010010001');
  122. $this->assertEquals($expected, $result);
  123. }
  124. /**
  125. * test that localized floats don't cause trouble.
  126. *
  127. * @group quoting
  128. * @return void
  129. */
  130. public function testLocalizedFloats() {
  131. $this->skipIf(DS === '\\', 'The locale is not supported in Windows and affect the others tests.');
  132. $restore = setlocale(LC_ALL, null);
  133. setlocale(LC_ALL, 'de_DE');
  134. $result = $this->Dbo->value(3.141593);
  135. $this->assertEquals('3.141593', $result);
  136. $result = $this->db->value(3.141593, 'float');
  137. $this->assertEquals('3.141593', $result);
  138. $result = $this->db->value(1234567.11, 'float');
  139. $this->assertEquals('1234567.11', $result);
  140. $result = $this->db->value(123456.45464748, 'float');
  141. $this->assertContains('123456.454647', $result);
  142. $result = $this->db->value(0.987654321, 'float');
  143. $this->assertEquals('0.987654321', (string)$result);
  144. $result = $this->db->value(2.2E-54, 'float');
  145. $this->assertEquals('2.2E-54', (string)$result);
  146. $result = $this->db->value(2.2E-54);
  147. $this->assertEquals('2.2E-54', (string)$result);
  148. setlocale(LC_ALL, $restore);
  149. }
  150. /**
  151. * test that scientific notations are working correctly
  152. *
  153. * @return void
  154. */
  155. function testScientificNotation() {
  156. $result = $this->db->value(2.2E-54, 'float');
  157. $this->assertEquals('2.2E-54', (string)$result);
  158. $result = $this->db->value(2.2E-54);
  159. $this->assertEquals('2.2E-54', (string)$result);
  160. }
  161. /**
  162. * testTinyintCasting method
  163. *
  164. *
  165. * @return void
  166. */
  167. public function testTinyintCasting() {
  168. $this->Dbo->cacheSources = false;
  169. $tableName = 'tinyint_' . uniqid();
  170. $this->Dbo->rawQuery('CREATE TABLE ' . $this->Dbo->fullTableName($tableName) . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id));');
  171. $this->model = new CakeTestModel(array(
  172. 'name' => 'Tinyint', 'table' => $tableName, 'ds' => 'test'
  173. ));
  174. $result = $this->model->schema();
  175. $this->assertEquals($result['bool']['type'], 'boolean');
  176. $this->assertEquals($result['small_int']['type'], 'integer');
  177. $this->assertTrue((bool)$this->model->save(array('bool' => 5, 'small_int' => 5)));
  178. $result = $this->model->find('first');
  179. $this->assertSame($result['Tinyint']['bool'], true);
  180. $this->assertSame($result['Tinyint']['small_int'], '5');
  181. $this->model->deleteAll(true);
  182. $this->assertTrue((bool)$this->model->save(array('bool' => 0, 'small_int' => 100)));
  183. $result = $this->model->find('first');
  184. $this->assertSame($result['Tinyint']['bool'], false);
  185. $this->assertSame($result['Tinyint']['small_int'], '100');
  186. $this->model->deleteAll(true);
  187. $this->assertTrue((bool)$this->model->save(array('bool' => true, 'small_int' => 0)));
  188. $result = $this->model->find('first');
  189. $this->assertSame($result['Tinyint']['bool'], true);
  190. $this->assertSame($result['Tinyint']['small_int'], '0');
  191. $this->model->deleteAll(true);
  192. $this->Dbo->rawQuery('DROP TABLE ' . $this->Dbo->fullTableName($tableName));
  193. }
  194. /**
  195. * testLastAffected method
  196. *
  197. *
  198. * @return void
  199. */
  200. public function testLastAffected() {
  201. $this->Dbo->cacheSources = false;
  202. $tableName = 'tinyint_' . uniqid();
  203. $this->Dbo->rawQuery('CREATE TABLE ' . $this->Dbo->fullTableName($tableName) . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id));');
  204. $this->model = new CakeTestModel(array(
  205. 'name' => 'Tinyint', 'table' => $tableName, 'ds' => 'test'
  206. ));
  207. $this->assertTrue((bool)$this->model->save(array('bool' => 5, 'small_int' => 5)));
  208. $this->assertEquals(1, $this->model->find('count'));
  209. $this->model->deleteAll(true);
  210. $result = $this->Dbo->lastAffected();
  211. $this->assertEquals(1, $result);
  212. $this->assertEquals(0, $this->model->find('count'));
  213. $this->Dbo->rawQuery('DROP TABLE ' . $this->Dbo->fullTableName($tableName));
  214. }
  215. /**
  216. * testIndexDetection method
  217. *
  218. * @group indices
  219. * @return void
  220. */
  221. public function testIndexDetection() {
  222. $this->Dbo->cacheSources = false;
  223. $name = $this->Dbo->fullTableName('simple');
  224. $this->Dbo->rawQuery('CREATE TABLE ' . $name . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id));');
  225. $expected = array('PRIMARY' => array('column' => 'id', 'unique' => 1));
  226. $result = $this->Dbo->index('simple', false);
  227. $this->Dbo->rawQuery('DROP TABLE ' . $name);
  228. $this->assertEquals($expected, $result);
  229. $name = $this->Dbo->fullTableName('with_a_key');
  230. $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` ));');
  231. $expected = array(
  232. 'PRIMARY' => array('column' => 'id', 'unique' => 1),
  233. 'pointless_bool' => array('column' => 'bool', 'unique' => 0),
  234. );
  235. $result = $this->Dbo->index('with_a_key', false);
  236. $this->Dbo->rawQuery('DROP TABLE ' . $name);
  237. $this->assertEquals($expected, $result);
  238. $name = $this->Dbo->fullTableName('with_two_keys');
  239. $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` ));');
  240. $expected = array(
  241. 'PRIMARY' => array('column' => 'id', 'unique' => 1),
  242. 'pointless_bool' => array('column' => 'bool', 'unique' => 0),
  243. 'pointless_small_int' => array('column' => 'small_int', 'unique' => 0),
  244. );
  245. $result = $this->Dbo->index('with_two_keys', false);
  246. $this->Dbo->rawQuery('DROP TABLE ' . $name);
  247. $this->assertEquals($expected, $result);
  248. $name = $this->Dbo->fullTableName('with_compound_keys');
  249. $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` ));');
  250. $expected = array(
  251. 'PRIMARY' => array('column' => 'id', 'unique' => 1),
  252. 'pointless_bool' => array('column' => 'bool', 'unique' => 0),
  253. 'pointless_small_int' => array('column' => 'small_int', 'unique' => 0),
  254. 'one_way' => array('column' => array('bool', 'small_int'), 'unique' => 0),
  255. );
  256. $result = $this->Dbo->index('with_compound_keys', false);
  257. $this->Dbo->rawQuery('DROP TABLE ' . $name);
  258. $this->assertEquals($expected, $result);
  259. $name = $this->Dbo->fullTableName('with_multiple_compound_keys');
  260. $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` ));');
  261. $expected = array(
  262. 'PRIMARY' => array('column' => 'id', 'unique' => 1),
  263. 'pointless_bool' => array('column' => 'bool', 'unique' => 0),
  264. 'pointless_small_int' => array('column' => 'small_int', 'unique' => 0),
  265. 'one_way' => array('column' => array('bool', 'small_int'), 'unique' => 0),
  266. 'other_way' => array('column' => array('small_int', 'bool'), 'unique' => 0),
  267. );
  268. $result = $this->Dbo->index('with_multiple_compound_keys', false);
  269. $this->Dbo->rawQuery('DROP TABLE ' . $name);
  270. $this->assertEquals($expected, $result);
  271. }
  272. /**
  273. * testBuildColumn method
  274. *
  275. * @return void
  276. */
  277. public function testBuildColumn() {
  278. $restore = $this->Dbo->columns;
  279. $this->Dbo->columns = array('varchar(255)' => 1);
  280. $data = array(
  281. 'name' => 'testName',
  282. 'type' => 'varchar(255)',
  283. 'default',
  284. 'null' => true,
  285. 'key',
  286. 'comment' => 'test'
  287. );
  288. $result = $this->Dbo->buildColumn($data);
  289. $expected = '`testName` DEFAULT NULL COMMENT \'test\'';
  290. $this->assertEquals($expected, $result);
  291. $data = array(
  292. 'name' => 'testName',
  293. 'type' => 'varchar(255)',
  294. 'default',
  295. 'null' => true,
  296. 'key',
  297. 'charset' => 'utf8',
  298. 'collate' => 'utf8_unicode_ci'
  299. );
  300. $result = $this->Dbo->buildColumn($data);
  301. $expected = '`testName` CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL';
  302. $this->assertEquals($expected, $result);
  303. $this->Dbo->columns = $restore;
  304. }
  305. /**
  306. * MySQL 4.x returns index data in a different format,
  307. * Using a mock ensure that MySQL 4.x output is properly parsed.
  308. *
  309. * @group indices
  310. * @return void
  311. */
  312. public function testIndexOnMySQL4Output() {
  313. $name = $this->Dbo->fullTableName('simple');
  314. $mockDbo = $this->getMock('Mysql', array('connect', '_execute', 'getVersion'));
  315. $columnData = array(
  316. array('0' => array(
  317. 'Table' => 'with_compound_keys',
  318. 'Non_unique' => '0',
  319. 'Key_name' => 'PRIMARY',
  320. 'Seq_in_index' => '1',
  321. 'Column_name' => 'id',
  322. 'Collation' => 'A',
  323. 'Cardinality' => '0',
  324. 'Sub_part' => NULL,
  325. 'Packed' => NULL,
  326. 'Null' => '',
  327. 'Index_type' => 'BTREE',
  328. 'Comment' => ''
  329. )),
  330. array('0' => array(
  331. 'Table' => 'with_compound_keys',
  332. 'Non_unique' => '1',
  333. 'Key_name' => 'pointless_bool',
  334. 'Seq_in_index' => '1',
  335. 'Column_name' => 'bool',
  336. 'Collation' => 'A',
  337. 'Cardinality' => NULL,
  338. 'Sub_part' => NULL,
  339. 'Packed' => NULL,
  340. 'Null' => 'YES',
  341. 'Index_type' => 'BTREE',
  342. 'Comment' => ''
  343. )),
  344. array('0' => array(
  345. 'Table' => 'with_compound_keys',
  346. 'Non_unique' => '1',
  347. 'Key_name' => 'pointless_small_int',
  348. 'Seq_in_index' => '1',
  349. 'Column_name' => 'small_int',
  350. 'Collation' => 'A',
  351. 'Cardinality' => NULL,
  352. 'Sub_part' => NULL,
  353. 'Packed' => NULL,
  354. 'Null' => 'YES',
  355. 'Index_type' => 'BTREE',
  356. 'Comment' => ''
  357. )),
  358. array('0' => array(
  359. 'Table' => 'with_compound_keys',
  360. 'Non_unique' => '1',
  361. 'Key_name' => 'one_way',
  362. 'Seq_in_index' => '1',
  363. 'Column_name' => 'bool',
  364. 'Collation' => 'A',
  365. 'Cardinality' => NULL,
  366. 'Sub_part' => NULL,
  367. 'Packed' => NULL,
  368. 'Null' => 'YES',
  369. 'Index_type' => 'BTREE',
  370. 'Comment' => ''
  371. )),
  372. array('0' => array(
  373. 'Table' => 'with_compound_keys',
  374. 'Non_unique' => '1',
  375. 'Key_name' => 'one_way',
  376. 'Seq_in_index' => '2',
  377. 'Column_name' => 'small_int',
  378. 'Collation' => 'A',
  379. 'Cardinality' => NULL,
  380. 'Sub_part' => NULL,
  381. 'Packed' => NULL,
  382. 'Null' => 'YES',
  383. 'Index_type' => 'BTREE',
  384. 'Comment' => ''
  385. ))
  386. );
  387. $mockDbo->expects($this->once())->method('getVersion')->will($this->returnValue('4.1'));
  388. $resultMock = $this->getMock('PDOStatement', array('fetch'));
  389. $mockDbo->expects($this->once())
  390. ->method('_execute')
  391. ->with('SHOW INDEX FROM ' . $name)
  392. ->will($this->returnValue($resultMock));
  393. foreach ($columnData as $i => $data) {
  394. $resultMock->expects($this->at($i))->method('fetch')->will($this->returnValue((object) $data));
  395. }
  396. $result = $mockDbo->index($name, false);
  397. $expected = array(
  398. 'PRIMARY' => array('column' => 'id', 'unique' => 1),
  399. 'pointless_bool' => array('column' => 'bool', 'unique' => 0),
  400. 'pointless_small_int' => array('column' => 'small_int', 'unique' => 0),
  401. 'one_way' => array('column' => array('bool', 'small_int'), 'unique' => 0),
  402. );
  403. $this->assertEquals($expected, $result);
  404. }
  405. /**
  406. * testColumn method
  407. *
  408. * @return void
  409. */
  410. public function testColumn() {
  411. $result = $this->Dbo->column('varchar(50)');
  412. $expected = 'string';
  413. $this->assertEquals($expected, $result);
  414. $result = $this->Dbo->column('text');
  415. $expected = 'text';
  416. $this->assertEquals($expected, $result);
  417. $result = $this->Dbo->column('int(11)');
  418. $expected = 'integer';
  419. $this->assertEquals($expected, $result);
  420. $result = $this->Dbo->column('int(11) unsigned');
  421. $expected = 'integer';
  422. $this->assertEquals($expected, $result);
  423. $result = $this->Dbo->column('tinyint(1)');
  424. $expected = 'boolean';
  425. $this->assertEquals($expected, $result);
  426. $result = $this->Dbo->column('boolean');
  427. $expected = 'boolean';
  428. $this->assertEquals($expected, $result);
  429. $result = $this->Dbo->column('float');
  430. $expected = 'float';
  431. $this->assertEquals($expected, $result);
  432. $result = $this->Dbo->column('float unsigned');
  433. $expected = 'float';
  434. $this->assertEquals($expected, $result);
  435. $result = $this->Dbo->column('double unsigned');
  436. $expected = 'float';
  437. $this->assertEquals($expected, $result);
  438. $result = $this->Dbo->column('decimal(14,7) unsigned');
  439. $expected = 'float';
  440. $this->assertEquals($expected, $result);
  441. }
  442. /**
  443. * testAlterSchemaIndexes method
  444. *
  445. * @group indices
  446. * @return void
  447. */
  448. public function testAlterSchemaIndexes() {
  449. $this->Dbo->cacheSources = $this->Dbo->testing = false;
  450. $table = $this->Dbo->fullTableName('altertest');
  451. $schema1 = new CakeSchema(array(
  452. 'name' => 'AlterTest1',
  453. 'connection' => 'test',
  454. 'altertest' => array(
  455. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  456. 'name' => array('type' => 'string', 'null' => false, 'length' => 50),
  457. 'group1' => array('type' => 'integer', 'null' => true),
  458. 'group2' => array('type' => 'integer', 'null' => true)
  459. )));
  460. $result = $this->Dbo->createSchema($schema1);
  461. $this->assertContains('`id` int(11) DEFAULT 0 NOT NULL,', $result);
  462. $this->assertContains('`name` varchar(50) NOT NULL,', $result);
  463. $this->assertContains('`group1` int(11) DEFAULT NULL', $result);
  464. $this->assertContains('`group2` int(11) DEFAULT NULL', $result);
  465. //Test that the string is syntactically correct
  466. $query = $this->Dbo->getConnection()->prepare($result);
  467. $this->assertEquals($result, $query->queryString);
  468. $schema2 = new CakeSchema(array(
  469. 'name' => 'AlterTest2',
  470. 'connection' => 'test',
  471. 'altertest' => array(
  472. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  473. 'name' => array('type' => 'string', 'null' => false, 'length' => 50),
  474. 'group1' => array('type' => 'integer', 'null' => true),
  475. 'group2' => array('type' => 'integer', 'null' => true),
  476. 'indexes' => array(
  477. 'name_idx' => array('column' => 'name', 'unique' => 0),
  478. 'group_idx' => array('column' => 'group1', 'unique' => 0),
  479. 'compound_idx' => array('column' => array('group1', 'group2'), 'unique' => 0),
  480. 'PRIMARY' => array('column' => 'id', 'unique' => 1))
  481. )));
  482. $result = $this->Dbo->alterSchema($schema2->compare($schema1));
  483. $this->assertContains("ALTER TABLE $table", $result);
  484. $this->assertContains('ADD KEY name_idx (`name`),', $result);
  485. $this->assertContains('ADD KEY group_idx (`group1`),', $result);
  486. $this->assertContains('ADD KEY compound_idx (`group1`, `group2`),', $result);
  487. $this->assertContains('ADD PRIMARY KEY (`id`);', $result);
  488. //Test that the string is syntactically correct
  489. $query = $this->Dbo->getConnection()->prepare($result);
  490. $this->assertEquals($result, $query->queryString);
  491. // Change three indexes, delete one and add another one
  492. $schema3 = new CakeSchema(array(
  493. 'name' => 'AlterTest3',
  494. 'connection' => 'test',
  495. 'altertest' => array(
  496. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  497. 'name' => array('type' => 'string', 'null' => false, 'length' => 50),
  498. 'group1' => array('type' => 'integer', 'null' => true),
  499. 'group2' => array('type' => 'integer', 'null' => true),
  500. 'indexes' => array(
  501. 'name_idx' => array('column' => 'name', 'unique' => 1),
  502. 'group_idx' => array('column' => 'group2', 'unique' => 0),
  503. 'compound_idx' => array('column' => array('group2', 'group1'), 'unique' => 0),
  504. 'id_name_idx' => array('column' => array('id', 'name'), 'unique' => 0))
  505. )));
  506. $result = $this->Dbo->alterSchema($schema3->compare($schema2));
  507. $this->assertContains("ALTER TABLE $table", $result);
  508. $this->assertContains('DROP PRIMARY KEY,', $result);
  509. $this->assertContains('DROP KEY name_idx,', $result);
  510. $this->assertContains('DROP KEY group_idx,', $result);
  511. $this->assertContains('DROP KEY compound_idx,', $result);
  512. $this->assertContains('ADD KEY id_name_idx (`id`, `name`),', $result);
  513. $this->assertContains('ADD UNIQUE KEY name_idx (`name`),', $result);
  514. $this->assertContains('ADD KEY group_idx (`group2`),', $result);
  515. $this->assertContains('ADD KEY compound_idx (`group2`, `group1`);', $result);
  516. $query = $this->Dbo->getConnection()->prepare($result);
  517. $this->assertEquals($result, $query->queryString);
  518. // Compare us to ourself.
  519. $this->assertEquals($schema3->compare($schema3), array());
  520. // Drop the indexes
  521. $result = $this->Dbo->alterSchema($schema1->compare($schema3));
  522. $this->assertContains("ALTER TABLE $table", $result);
  523. $this->assertContains('DROP KEY name_idx,', $result);
  524. $this->assertContains('DROP KEY group_idx,', $result);
  525. $this->assertContains('DROP KEY compound_idx,', $result);
  526. $this->assertContains('DROP KEY id_name_idx;', $result);
  527. $query = $this->Dbo->getConnection()->prepare($result);
  528. $this->assertEquals($result, $query->queryString);
  529. }
  530. /**
  531. * test saving and retrieval of blobs
  532. *
  533. * @return void
  534. */
  535. public function testBlobSaving() {
  536. $this->loadFixtures('BinaryTest');
  537. $this->Dbo->cacheSources = false;
  538. $data = file_get_contents(CAKE . 'Test' . DS . 'test_app' . DS . 'webroot' . DS . 'img' . DS . 'cake.power.gif');
  539. $model = new CakeTestModel(array('name' => 'BinaryTest', 'ds' => 'test'));
  540. $model->save(compact('data'));
  541. $result = $model->find('first');
  542. $this->assertEquals($result['BinaryTest']['data'], $data);
  543. }
  544. /**
  545. * test altering the table settings with schema.
  546. *
  547. * @return void
  548. */
  549. public function testAlteringTableParameters() {
  550. $this->Dbo->cacheSources = $this->Dbo->testing = false;
  551. $schema1 = new CakeSchema(array(
  552. 'name' => 'AlterTest1',
  553. 'connection' => 'test',
  554. 'altertest' => array(
  555. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  556. 'name' => array('type' => 'string', 'null' => false, 'length' => 50),
  557. 'tableParameters' => array(
  558. 'charset' => 'latin1',
  559. 'collate' => 'latin1_general_ci',
  560. 'engine' => 'MyISAM'
  561. )
  562. )
  563. ));
  564. $this->Dbo->rawQuery($this->Dbo->createSchema($schema1));
  565. $schema2 = new CakeSchema(array(
  566. 'name' => 'AlterTest1',
  567. 'connection' => 'test',
  568. 'altertest' => array(
  569. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  570. 'name' => array('type' => 'string', 'null' => false, 'length' => 50),
  571. 'tableParameters' => array(
  572. 'charset' => 'utf8',
  573. 'collate' => 'utf8_general_ci',
  574. 'engine' => 'InnoDB'
  575. )
  576. )
  577. ));
  578. $result = $this->Dbo->alterSchema($schema2->compare($schema1));
  579. $this->assertContains('DEFAULT CHARSET=utf8', $result);
  580. $this->assertContains('ENGINE=InnoDB', $result);
  581. $this->assertContains('COLLATE=utf8_general_ci', $result);
  582. $this->Dbo->rawQuery($result);
  583. $result = $this->Dbo->listDetailedSources($this->Dbo->fullTableName('altertest', false));
  584. $this->assertEquals($result['Collation'], 'utf8_general_ci');
  585. $this->assertEquals($result['Engine'], 'InnoDB');
  586. $this->assertEquals($result['charset'], 'utf8');
  587. $this->Dbo->rawQuery($this->Dbo->dropSchema($schema1));
  588. }
  589. /**
  590. * test alterSchema on two tables.
  591. *
  592. * @return void
  593. */
  594. public function testAlteringTwoTables() {
  595. $schema1 = new CakeSchema(array(
  596. 'name' => 'AlterTest1',
  597. 'connection' => 'test',
  598. 'altertest' => array(
  599. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  600. 'name' => array('type' => 'string', 'null' => false, 'length' => 50),
  601. ),
  602. 'other_table' => array(
  603. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  604. 'name' => array('type' => 'string', 'null' => false, 'length' => 50),
  605. )
  606. ));
  607. $schema2 = new CakeSchema(array(
  608. 'name' => 'AlterTest1',
  609. 'connection' => 'test',
  610. 'altertest' => array(
  611. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  612. 'field_two' => array('type' => 'string', 'null' => false, 'length' => 50),
  613. ),
  614. 'other_table' => array(
  615. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  616. 'field_two' => array('type' => 'string', 'null' => false, 'length' => 50),
  617. )
  618. ));
  619. $result = $this->Dbo->alterSchema($schema2->compare($schema1));
  620. $this->assertEquals(2, substr_count($result, 'field_two'), 'Too many fields');
  621. }
  622. /**
  623. * testReadTableParameters method
  624. *
  625. * @return void
  626. */
  627. public function testReadTableParameters() {
  628. $this->Dbo->cacheSources = $this->Dbo->testing = false;
  629. $tableName = 'tinyint_' . uniqid();
  630. $table = $this->Dbo->fullTableName($tableName);
  631. $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;');
  632. $result = $this->Dbo->readTableParameters($this->Dbo->fullTableName($tableName, false));
  633. $this->Dbo->rawQuery('DROP TABLE ' . $table);
  634. $expected = array(
  635. 'charset' => 'utf8',
  636. 'collate' => 'utf8_unicode_ci',
  637. 'engine' => 'InnoDB');
  638. $this->assertEquals($expected, $result);
  639. $table = $this->Dbo->fullTableName($tableName);
  640. $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;');
  641. $result = $this->Dbo->readTableParameters($this->Dbo->fullTableName($tableName, false));
  642. $this->Dbo->rawQuery('DROP TABLE ' . $table);
  643. $expected = array(
  644. 'charset' => 'cp1250',
  645. 'collate' => 'cp1250_general_ci',
  646. 'engine' => 'MyISAM');
  647. $this->assertEquals($expected, $result);
  648. }
  649. /**
  650. * testBuildTableParameters method
  651. *
  652. * @return void
  653. */
  654. public function testBuildTableParameters() {
  655. $this->Dbo->cacheSources = $this->Dbo->testing = false;
  656. $data = array(
  657. 'charset' => 'utf8',
  658. 'collate' => 'utf8_unicode_ci',
  659. 'engine' => 'InnoDB');
  660. $result = $this->Dbo->buildTableParameters($data);
  661. $expected = array(
  662. 'DEFAULT CHARSET=utf8',
  663. 'COLLATE=utf8_unicode_ci',
  664. 'ENGINE=InnoDB');
  665. $this->assertEquals($expected, $result);
  666. }
  667. /**
  668. * testBuildTableParameters method
  669. *
  670. * @return void
  671. */
  672. public function testGetCharsetName() {
  673. $this->Dbo->cacheSources = $this->Dbo->testing = false;
  674. $result = $this->Dbo->getCharsetName('utf8_unicode_ci');
  675. $this->assertEquals($result, 'utf8');
  676. $result = $this->Dbo->getCharsetName('cp1250_general_ci');
  677. $this->assertEquals($result, 'cp1250');
  678. }
  679. /**
  680. * test that changing the virtualFieldSeparator allows for __ fields.
  681. *
  682. * @return void
  683. */
  684. public function testVirtualFieldSeparators() {
  685. $this->loadFixtures('BinaryTest');
  686. $model = new CakeTestModel(array('table' => 'binary_tests', 'ds' => 'test', 'name' => 'BinaryTest'));
  687. $model->virtualFields = array(
  688. 'other__field' => 'SUM(id)'
  689. );
  690. $this->Dbo->virtualFieldSeparator = '_$_';
  691. $result = $this->Dbo->fields($model, null, array('data', 'other__field'));
  692. $expected = array('`BinaryTest`.`data`', '(SUM(id)) AS `BinaryTest_$_other__field`');
  693. $this->assertEquals($expected, $result);
  694. }
  695. /**
  696. * Test describe() on a fixture.
  697. *
  698. * @return void
  699. */
  700. public function testDescribe() {
  701. $this->loadFixtures('Apple');
  702. $model = new Apple();
  703. $result = $this->Dbo->describe($model);
  704. $this->assertTrue(isset($result['id']));
  705. $this->assertTrue(isset($result['color']));
  706. $result = $this->Dbo->describe($model->useTable);
  707. $this->assertTrue(isset($result['id']));
  708. $this->assertTrue(isset($result['color']));
  709. }
  710. /**
  711. * test that a describe() gets additional fieldParameters
  712. *
  713. * @return void
  714. */
  715. public function testDescribeGettingFieldParameters() {
  716. $schema = new CakeSchema(array(
  717. 'connection' => 'test',
  718. 'testdescribes' => array(
  719. 'id' => array('type' => 'integer', 'key' => 'primary'),
  720. 'stringy' => array(
  721. 'type' => 'string',
  722. 'null' => true,
  723. 'charset' => 'cp1250',
  724. 'collate' => 'cp1250_general_ci',
  725. ),
  726. 'other_col' => array(
  727. 'type' => 'string',
  728. 'null' => false,
  729. 'charset' => 'latin1',
  730. 'comment' => 'Test Comment'
  731. )
  732. )
  733. ));
  734. $this->Dbo->execute($this->Dbo->createSchema($schema));
  735. $model = new CakeTestModel(array('table' => 'testdescribes', 'name' => 'Testdescribes'));
  736. $result = $model->getDataSource()->describe($model);
  737. $this->Dbo->execute($this->Dbo->dropSchema($schema));
  738. $this->assertEquals($result['stringy']['collate'], 'cp1250_general_ci');
  739. $this->assertEquals($result['stringy']['charset'], 'cp1250');
  740. $this->assertEquals($result['other_col']['comment'], 'Test Comment');
  741. }
  742. /**
  743. * Tests that listSources method sends the correct query and parses the result accordingly
  744. * @return void
  745. */
  746. public function testListSources() {
  747. $db = $this->getMock('Mysql', array('connect', '_execute'));
  748. $queryResult = $this->getMock('PDOStatement');
  749. $db->expects($this->once())
  750. ->method('_execute')
  751. ->with('SHOW TABLES FROM `cake`')
  752. ->will($this->returnValue($queryResult));
  753. $queryResult->expects($this->at(0))
  754. ->method('fetch')
  755. ->will($this->returnValue(array('cake_table')));
  756. $queryResult->expects($this->at(1))
  757. ->method('fetch')
  758. ->will($this->returnValue(array('another_table')));
  759. $queryResult->expects($this->at(2))
  760. ->method('fetch')
  761. ->will($this->returnValue(null));
  762. $tables = $db->listSources();
  763. $this->assertEquals($tables, array('cake_table', 'another_table'));
  764. }
  765. /**
  766. * test that listDetailedSources with a named table that doesn't exist.
  767. *
  768. * @return void
  769. */
  770. public function testListDetailedSourcesNamed() {
  771. $this->loadFixtures('Apple');
  772. $result = $this->Dbo->listDetailedSources('imaginary');
  773. $this->assertEquals(array(), $result, 'Should be empty when table does not exist.');
  774. $result = $this->Dbo->listDetailedSources();
  775. $tableName = $this->Dbo->fullTableName('apples', false);
  776. $this->assertTrue(isset($result[$tableName]), 'Key should exist');
  777. }
  778. /**
  779. * Tests that getVersion method sends the correct query for getting the mysql version
  780. * @return void
  781. */
  782. public function testGetVersion() {
  783. $version = $this->Dbo->getVersion();
  784. $this->assertTrue(is_string($version));
  785. }
  786. /**
  787. * Tests that getVersion method sends the correct query for getting the client encoding
  788. * @return void
  789. */
  790. public function testGetEncoding() {
  791. $db = $this->getMock('Mysql', array('connect', '_execute'));
  792. $queryResult = $this->getMock('PDOStatement');
  793. $db->expects($this->once())
  794. ->method('_execute')
  795. ->with('SHOW VARIABLES LIKE ?', array('character_set_client'))
  796. ->will($this->returnValue($queryResult));
  797. $result = new StdClass;
  798. $result->Value = 'utf-8';
  799. $queryResult->expects($this->once())
  800. ->method('fetchObject')
  801. ->will($this->returnValue($result));
  802. $encoding = $db->getEncoding();
  803. $this->assertEquals('utf-8', $encoding);
  804. }
  805. /**
  806. * testFieldDoubleEscaping method
  807. *
  808. * @return void
  809. */
  810. public function testFieldDoubleEscaping() {
  811. $test = $this->getMock('Mysql', array('connect', '_execute', 'execute'));
  812. $this->Model = $this->getMock('Article2', array('getDataSource'));
  813. $this->Model->alias = 'Article';
  814. $this->Model->expects($this->any())
  815. ->method('getDataSource')
  816. ->will($this->returnValue($test));
  817. $this->assertEquals($this->Model->escapeField(), '`Article`.`id`');
  818. $result = $test->fields($this->Model, null, $this->Model->escapeField());
  819. $this->assertEquals($result, array('`Article`.`id`'));
  820. $test->expects($this->at(0))->method('execute')
  821. ->with('SELECT `Article`.`id` FROM `articles` AS `Article` WHERE 1 = 1');
  822. $result = $test->read($this->Model, array(
  823. 'fields' => $this->Model->escapeField(),
  824. 'conditions' => null,
  825. 'recursive' => -1
  826. ));
  827. $test->startQuote = '[';
  828. $test->endQuote = ']';
  829. $this->assertEquals($this->Model->escapeField(), '[Article].[id]');
  830. $result = $test->fields($this->Model, null, $this->Model->escapeField());
  831. $this->assertEquals($result, array('[Article].[id]'));
  832. $test->expects($this->at(0))->method('execute')
  833. ->with('SELECT [Article].[id] FROM [' . $test->fullTableName('articles', false) . '] AS [Article] WHERE 1 = 1');
  834. $result = $test->read($this->Model, array(
  835. 'fields' => $this->Model->escapeField(),
  836. 'conditions' => null,
  837. 'recursive' => -1
  838. ));
  839. }
  840. /**
  841. * testGenerateAssociationQuerySelfJoin method
  842. *
  843. * @return void
  844. */
  845. public function testGenerateAssociationQuerySelfJoin() {
  846. $this->Dbo = $this->getMock('Mysql', array('connect', '_execute', 'execute'));
  847. $this->startTime = microtime(true);
  848. $this->Model = new Article2();
  849. $this->_buildRelatedModels($this->Model);
  850. $this->_buildRelatedModels($this->Model->Category2);
  851. $this->Model->Category2->ChildCat = new Category2();
  852. $this->Model->Category2->ParentCat = new Category2();
  853. $queryData = array();
  854. foreach ($this->Model->Category2->associations() as $type) {
  855. foreach ($this->Model->Category2->{$type} as $assoc => $assocData) {
  856. $linkModel = $this->Model->Category2->{$assoc};
  857. $external = isset($assocData['external']);
  858. if ($this->Model->Category2->alias == $linkModel->alias && $type != 'hasAndBelongsToMany' && $type != 'hasMany') {
  859. $result = $this->Dbo->generateAssociationQuery($this->Model->Category2, $linkModel, $type, $assoc, $assocData, $queryData, $external, $null);
  860. $this->assertFalse(empty($result));
  861. } else {
  862. if ($this->Model->Category2->useDbConfig == $linkModel->useDbConfig) {
  863. $result = $this->Dbo->generateAssociationQuery($this->Model->Category2, $linkModel, $type, $assoc, $assocData, $queryData, $external, $null);
  864. $this->assertFalse(empty($result));
  865. }
  866. }
  867. }
  868. }
  869. $query = $this->Dbo->generateAssociationQuery($this->Model->Category2, $null, null, null, null, $queryData, false, $null);
  870. $this->assertRegExp('/^SELECT\s+(.+)FROM(.+)`Category2`\.`group_id`\s+=\s+`Group`\.`id`\)\s+LEFT JOIN(.+)WHERE\s+1 = 1\s*$/', $query);
  871. $this->Model = new TestModel4();
  872. $this->Model->schema();
  873. $this->_buildRelatedModels($this->Model);
  874. $binding = array('type' => 'belongsTo', 'model' => 'TestModel4Parent');
  875. $queryData = array();
  876. $resultSet = null;
  877. $null = null;
  878. $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
  879. $_queryData = $queryData;
  880. $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
  881. $this->assertTrue($result);
  882. $expected = array(
  883. 'conditions' => array(),
  884. 'fields' => array(
  885. '`TestModel4`.`id`',
  886. '`TestModel4`.`name`',
  887. '`TestModel4`.`created`',
  888. '`TestModel4`.`updated`',
  889. '`TestModel4Parent`.`id`',
  890. '`TestModel4Parent`.`name`',
  891. '`TestModel4Parent`.`created`',
  892. '`TestModel4Parent`.`updated`'
  893. ),
  894. 'joins' => array(
  895. array(
  896. 'table' => '`test_model4`',
  897. 'alias' => 'TestModel4Parent',
  898. 'type' => 'LEFT',
  899. 'conditions' => '`TestModel4`.`parent_id` = `TestModel4Parent`.`id`'
  900. )
  901. ),
  902. 'order' => array(),
  903. 'limit' => array(),
  904. 'offset' => array(),
  905. 'group' => array(),
  906. 'callbacks' => null
  907. );
  908. $queryData['joins'][0]['table'] = $this->Dbo->fullTableName($queryData['joins'][0]['table']);
  909. $this->assertEquals($queryData, $expected);
  910. $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
  911. $this->assertRegExp('/^SELECT\s+`TestModel4`\.`id`, `TestModel4`\.`name`, `TestModel4`\.`created`, `TestModel4`\.`updated`, `TestModel4Parent`\.`id`, `TestModel4Parent`\.`name`, `TestModel4Parent`\.`created`, `TestModel4Parent`\.`updated`\s+/', $result);
  912. $this->assertRegExp('/FROM\s+`test_model4` AS `TestModel4`\s+LEFT JOIN\s+`test_model4` AS `TestModel4Parent`/', $result);
  913. $this->assertRegExp('/\s+ON\s+\(`TestModel4`.`parent_id` = `TestModel4Parent`.`id`\)\s+WHERE/', $result);
  914. $this->assertRegExp('/\s+WHERE\s+1 = 1\s+$/', $result);
  915. $params['assocData']['type'] = 'INNER';
  916. $this->Model->belongsTo['TestModel4Parent']['type'] = 'INNER';
  917. $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $_queryData, $params['external'], $resultSet);
  918. $this->assertTrue($result);
  919. $this->assertEquals($_queryData['joins'][0]['type'], 'INNER');
  920. }
  921. /**
  922. * buildRelatedModels method
  923. *
  924. * @param mixed $model
  925. * @return void
  926. */
  927. function _buildRelatedModels($model) {
  928. foreach ($model->associations() as $type) {
  929. foreach ($model->{$type} as $assoc => $assocData) {
  930. if (is_string($assocData)) {
  931. $className = $assocData;
  932. } elseif (isset($assocData['className'])) {
  933. $className = $assocData['className'];
  934. }
  935. $model->$className = new $className();
  936. $model->$className->schema();
  937. }
  938. }
  939. }
  940. /**
  941. * &_prepareAssociationQuery method
  942. *
  943. * @param mixed $model
  944. * @param mixed $queryData
  945. * @param mixed $binding
  946. * @return void
  947. */
  948. function &_prepareAssociationQuery($model, &$queryData, $binding) {
  949. $type = $binding['type'];
  950. $assoc = $binding['model'];
  951. $assocData = $model->{$type}[$assoc];
  952. $className = $assocData['className'];
  953. $linkModel = $model->{$className};
  954. $external = isset($assocData['external']);
  955. $reflection = new ReflectionMethod($this->Dbo, '_scrubQueryData');
  956. $reflection->setAccessible(true);
  957. $queryData = $reflection->invokeArgs($this->Dbo, array($queryData));
  958. $result = array_merge(array('linkModel' => &$linkModel), compact('type', 'assoc', 'assocData', 'external'));
  959. return $result;
  960. }
  961. /**
  962. * testGenerateInnerJoinAssociationQuery method
  963. *
  964. * @return void
  965. */
  966. public function testGenerateInnerJoinAssociationQuery() {
  967. $test = $this->getMock('Mysql', array('connect', '_execute', 'execute'));
  968. $this->Model = $this->getMock('TestModel9', array('getDataSource'));
  969. $this->Model->expects($this->any())
  970. ->method('getDataSource')
  971. ->will($this->returnValue($test));
  972. $this->Model->TestModel8 = $this->getMock('TestModel8', array('getDataSource'));
  973. $this->Model->TestModel8->expects($this->any())
  974. ->method('getDataSource')
  975. ->will($this->returnValue($test));
  976. $test->expects($this->at(0))->method('execute')
  977. ->with($this->stringContains('`TestModel9` LEFT JOIN `test_model8`'));
  978. $test->expects($this->at(1))->method('execute')
  979. ->with($this->stringContains('TestModel9` INNER JOIN `test_model8`'));
  980. $test->read($this->Model, array('recursive' => 1));
  981. $this->Model->belongsTo['TestModel8']['type'] = 'INNER';
  982. $test->read($this->Model, array('recursive' => 1));
  983. }
  984. /**
  985. * testGenerateAssociationQuerySelfJoinWithConditionsInHasOneBinding method
  986. *
  987. * @return void
  988. */
  989. public function testGenerateAssociationQuerySelfJoinWithConditionsInHasOneBinding() {
  990. $this->Model = new TestModel8();
  991. $this->Model->schema();
  992. $this->_buildRelatedModels($this->Model);
  993. $binding = array('type' => 'hasOne', 'model' => 'TestModel9');
  994. $queryData = array();
  995. $resultSet = null;
  996. $null = null;
  997. $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
  998. $_queryData = $queryData;
  999. $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
  1000. $this->assertTrue($result);
  1001. $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
  1002. $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);
  1003. $this->assertRegExp('/FROM\s+`test_model8` AS `TestModel8`\s+LEFT JOIN\s+`test_model9` AS `TestModel9`/', $result);
  1004. $this->assertRegExp('/\s+ON\s+\(`TestModel9`\.`name` != \'mariano\'\s+AND\s+`TestModel9`.`test_model8_id` = `TestModel8`.`id`\)\s+WHERE/', $result);
  1005. $this->assertRegExp('/\s+WHERE\s+(?:\()?1\s+=\s+1(?:\))?\s*$/', $result);
  1006. }
  1007. /**
  1008. * testGenerateAssociationQuerySelfJoinWithConditionsInBelongsToBinding method
  1009. *
  1010. * @return void
  1011. */
  1012. public function testGenerateAssociationQuerySelfJoinWithConditionsInBelongsToBinding() {
  1013. $this->Model = new TestModel9();
  1014. $this->Model->schema();
  1015. $this->_buildRelatedModels($this->Model);
  1016. $binding = array('type' => 'belongsTo', 'model' => 'TestModel8');
  1017. $queryData = array();
  1018. $resultSet = null;
  1019. $null = null;
  1020. $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
  1021. $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
  1022. $this->assertTrue($result);
  1023. $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
  1024. $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);
  1025. $this->assertRegExp('/FROM\s+`test_model9` AS `TestModel9`\s+LEFT JOIN\s+`test_model8` AS `TestModel8`/', $result);
  1026. $this->assertRegExp('/\s+ON\s+\(`TestModel8`\.`name` != \'larry\'\s+AND\s+`TestModel9`.`test_model8_id` = `TestModel8`.`id`\)\s+WHERE/', $result);
  1027. $this->assertRegExp('/\s+WHERE\s+(?:\()?1\s+=\s+1(?:\))?\s*$/', $result);
  1028. }
  1029. /**
  1030. * testGenerateAssociationQuerySelfJoinWithConditions method
  1031. *
  1032. * @return void
  1033. */
  1034. public function testGenerateAssociationQuerySelfJoinWithConditions() {
  1035. $this->Model = new TestModel4();
  1036. $this->Model->schema();
  1037. $this->_buildRelatedModels($this->Model);
  1038. $binding = array('type' => 'belongsTo', 'model' => 'TestModel4Parent');
  1039. $queryData = array('conditions' => array('TestModel4Parent.name !=' => 'mariano'));
  1040. $resultSet = null;
  1041. $null = null;
  1042. $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
  1043. $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
  1044. $this->assertTrue($result);
  1045. $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
  1046. $this->assertRegExp('/^SELECT\s+`TestModel4`\.`id`, `TestModel4`\.`name`, `TestModel4`\.`created`, `TestModel4`\.`updated`, `TestModel4Parent`\.`id`, `TestModel4Parent`\.`name`, `TestModel4Parent`\.`created`, `TestModel4Parent`\.`updated`\s+/', $result);
  1047. $this->assertRegExp('/FROM\s+`test_model4` AS `TestModel4`\s+LEFT JOIN\s+`test_model4` AS `TestModel4Parent`/', $result);
  1048. $this->assertRegExp('/\s+ON\s+\(`TestModel4`.`parent_id` = `TestModel4Parent`.`id`\)\s+WHERE/', $result);
  1049. $this->assertRegExp('/\s+WHERE\s+(?:\()?`TestModel4Parent`.`name`\s+!=\s+\'mariano\'(?:\))?\s*$/', $result);
  1050. $this->Featured2 = new Featured2();
  1051. $this->Featured2->schema();
  1052. $this->Featured2->bindModel(array(
  1053. 'belongsTo' => array(
  1054. 'ArticleFeatured2' => array(
  1055. 'conditions' => 'ArticleFeatured2.published = \'Y\'',
  1056. 'fields' => 'id, title, user_id, published'
  1057. )
  1058. )
  1059. ));
  1060. $this->_buildRelatedModels($this->Featured2);
  1061. $binding = array('type' => 'belongsTo', 'model' => 'ArticleFeatured2');
  1062. $queryData = array('conditions' => array());
  1063. $resultSet = null;
  1064. $null = null;
  1065. $params = &$this->_prepareAssociationQuery($this->Featured2, $queryData, $binding);
  1066. $result = $this->Dbo->generateAssociationQuery($this->Featured2, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
  1067. $this->assertTrue($result);
  1068. $result = $this->Dbo->generateAssociationQuery($this->Featured2, $null, null, null, null, $queryData, false, $null);
  1069. $this->assertRegExp(
  1070. '/^SELECT\s+`Featured2`\.`id`, `Featured2`\.`article_id`, `Featured2`\.`category_id`, `Featured2`\.`name`,\s+'.
  1071. '`ArticleFeatured2`\.`id`, `ArticleFeatured2`\.`title`, `ArticleFeatured2`\.`user_id`, `ArticleFeatured2`\.`published`\s+' .
  1072. 'FROM\s+`featured2` AS `Featured2`\s+LEFT JOIN\s+`article_featured` AS `ArticleFeatured2`' .
  1073. '\s+ON\s+\(`ArticleFeatured2`.`published` = \'Y\'\s+AND\s+`Featured2`\.`article_featured2_id` = `ArticleFeatured2`\.`id`\)' .
  1074. '\s+WHERE\s+1\s+=\s+1\s*$/',
  1075. $result
  1076. );
  1077. }
  1078. /**
  1079. * testGenerateAssociationQueryHasOne method
  1080. *
  1081. * @return void
  1082. */
  1083. public function testGenerateAssociationQueryHasOne() {
  1084. $this->Model = new TestModel4();
  1085. $this->Model->schema();
  1086. $this->_buildRelatedModels($this->Model);
  1087. $binding = array('type' => 'hasOne', 'model' => 'TestModel5');
  1088. $queryData = array();
  1089. $resultSet = null;
  1090. $null = null;
  1091. $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
  1092. $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
  1093. $this->assertTrue($result);
  1094. $result = $this->Dbo->buildJoinStatement($queryData['joins'][0]);
  1095. $expected = ' LEFT JOIN `test_model5` AS `TestModel5` ON (`TestModel5`.`test_model4_id` = `TestModel4`.`id`)';
  1096. $this->assertEquals(trim($result), trim($expected));
  1097. $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
  1098. $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);
  1099. $this->assertRegExp('/\s+FROM\s+`test_model4` AS `TestModel4`\s+LEFT JOIN\s+/', $result);
  1100. $this->assertRegExp('/`test_model5` AS `TestModel5`\s+ON\s+\(`TestModel5`.`test_model4_id` = `TestModel4`.`id`\)\s+WHERE/', $result);
  1101. $this->assertRegExp('/\s+WHERE\s+(?:\()?\s*1 = 1\s*(?:\))?\s*$/', $result);
  1102. }
  1103. /**
  1104. * testGenerateAssociationQueryHasOneWithConditions method
  1105. *
  1106. * @return void
  1107. */
  1108. public function testGenerateAssociationQueryHasOneWithConditions() {
  1109. $this->Model = new TestModel4();
  1110. $this->Model->schema();
  1111. $this->_buildRelatedModels($this->Model);
  1112. $binding = array('type' => 'hasOne', 'model' => 'TestModel5');
  1113. $queryData = array('conditions' => array('TestModel5.name !=' => 'mariano'));
  1114. $resultSet = null;
  1115. $null = null;
  1116. $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
  1117. $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
  1118. $this->assertTrue($result);
  1119. $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
  1120. $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);
  1121. $this->assertRegExp('/\s+FROM\s+`test_model4` AS `TestModel4`\s+LEFT JOIN\s+`test_model5` AS `TestModel5`/', $result);
  1122. $this->assertRegExp('/\s+ON\s+\(`TestModel5`.`test_model4_id`\s+=\s+`TestModel4`.`id`\)\s+WHERE/', $result);
  1123. $this->assertRegExp('/\s+WHERE\s+(?:\()?\s*`TestModel5`.`name`\s+!=\s+\'mariano\'\s*(?:\))?\s*$/', $result);
  1124. }
  1125. /**
  1126. * testGenerateAssociationQueryBelongsTo method
  1127. *
  1128. * @return void
  1129. */
  1130. public function testGenerateAssociationQueryBelongsTo() {
  1131. $this->Model = new TestModel5();
  1132. $this->Model->schema();
  1133. $this->_buildRelatedModels($this->Model);
  1134. $binding = array('type' => 'belongsTo', 'model' => 'TestModel4');
  1135. $queryData = array();
  1136. $resultSet = null;
  1137. $null = null;
  1138. $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
  1139. $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
  1140. $this->assertTrue($result);
  1141. $result = $this->Dbo->buildJoinStatement($queryData['joins'][0]);
  1142. $expected = ' LEFT JOIN `test_model4` AS `TestModel4` ON (`TestModel5`.`test_model4_id` = `TestModel4`.`id`)';
  1143. $this->assertEquals(trim($result), trim($expected));
  1144. $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
  1145. $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);
  1146. $this->assertRegExp('/\s+FROM\s+`test_model5` AS `TestModel5`\s+LEFT JOIN\s+`test_model4` AS `TestModel4`/', $result);
  1147. $this->assertRegExp('/\s+ON\s+\(`TestModel5`.`test_model4_id` = `TestModel4`.`id`\)\s+WHERE\s+/', $result);
  1148. $this->assertRegExp('/\s+WHERE\s+(?:\()?\s*1 = 1\s*(?:\))?\s*$/', $result);
  1149. }
  1150. /**
  1151. * testGenerateAssociationQueryBelongsToWithConditions method
  1152. *
  1153. * @return void
  1154. */
  1155. public function testGenerateAssociationQueryBelongsToWithConditions() {
  1156. $this->Model = new TestModel5();
  1157. $this->Model->schema();
  1158. $this->_buildRelatedModels($this->Model);
  1159. $binding = array('type' => 'belongsTo', 'model' => 'TestModel4');
  1160. $queryData = array('conditions' => array('TestModel5.name !=' => 'mariano'));
  1161. $resultSet = null;
  1162. $null = null;
  1163. $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
  1164. $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
  1165. $this->assertTrue($result);
  1166. $result = $this->Dbo->buildJoinStatement($queryData['joins'][0]);
  1167. $expected = ' LEFT JOIN `test_model4` AS `TestModel4` ON (`TestModel5`.`test_model4_id` = `TestModel4`.`id`)';
  1168. $this->assertEquals(trim($result), trim($expected));
  1169. $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
  1170. $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);
  1171. $this->assertRegExp('/\s+FROM\s+`test_model5` AS `TestModel5`\s+LEFT JOIN\s+`test_model4` AS `TestModel4`/', $result);
  1172. $this->assertRegExp('/\s+ON\s+\(`TestModel5`.`test_model4_id` = `TestModel4`.`id`\)\s+WHERE\s+/', $result);
  1173. $this->assertRegExp('/\s+WHERE\s+`TestModel5`.`name` != \'mariano\'\s*$/', $result);
  1174. }
  1175. /**
  1176. * testGenerateAssociationQueryHasMany method
  1177. *
  1178. * @return void
  1179. */
  1180. public function testGenerateAssociationQueryHasMany() {
  1181. $this->Model = new TestModel5();
  1182. $this->Model->schema();
  1183. $this->_buildRelatedModels($this->Model);
  1184. $binding = array('type' => 'hasMany', 'model' => 'TestModel6');
  1185. $queryData = array();
  1186. $resultSet = null;
  1187. $null = null;
  1188. $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
  1189. $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
  1190. $this->assertRegExp('/^SELECT\s+`TestModel6`\.`id`, `TestModel6`\.`test_model5_id`, `TestModel6`\.`name`, `TestModel6`\.`created`, `TestModel6`\.`updated`\s+/', $result);
  1191. $this->assertRegExp('/\s+FROM\s+`test_model6` AS `TestModel6`\s+WHERE/', $result);
  1192. $this->assertRegExp('/\s+WHERE\s+`TestModel6`.`test_model5_id`\s+=\s+\({\$__cakeID__\$}\)/', $result);
  1193. $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
  1194. $this->assertRegExp('/^SELECT\s+`TestModel5`\.`id`, `TestModel5`\.`test_model4_id`, `TestModel5`\.`name`, `TestModel5`\.`created`, `TestModel5`\.`updated`\s+/', $result);
  1195. $this->assertRegExp('/\s+FROM\s+`test_model5` AS `TestModel5`\s+WHERE\s+/', $result);
  1196. $this->assertRegExp('/\s+WHERE\s+(?:\()?\s*1 = 1\s*(?:\))?\s*$/', $result);
  1197. }
  1198. /**
  1199. * testGenerateAssociationQueryHasManyWithLimit method
  1200. *
  1201. * @return void
  1202. */
  1203. public function testGenerateAssociationQueryHasManyWithLimit() {
  1204. $this->Model = new TestModel5();
  1205. $this->Model->schema();
  1206. $this->_buildRelatedModels($this->Model);
  1207. $this->Model->hasMany['TestModel6']['limit'] = 2;
  1208. $binding = array('type' => 'hasMany', 'model' => 'TestModel6');
  1209. $queryData = array();
  1210. $resultSet = null;
  1211. $null = null;
  1212. $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
  1213. $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
  1214. $this->assertRegExp(
  1215. '/^SELECT\s+' .
  1216. '`TestModel6`\.`id`, `TestModel6`\.`test_model5_id`, `TestModel6`\.`name`, `TestModel6`\.`created`, `TestModel6`\.`updated`\s+'.
  1217. 'FROM\s+`test_model6` AS `TestModel6`\s+WHERE\s+' .
  1218. '`TestModel6`.`test_model5_id`\s+=\s+\({\$__cakeID__\$}\)\s*'.
  1219. 'LIMIT \d*'.
  1220. '\s*$/', $result
  1221. );
  1222. $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
  1223. $this->assertRegExp(
  1224. '/^SELECT\s+'.
  1225. '`TestModel5`\.`id`, `TestModel5`\.`test_model4_id`, `TestModel5`\.`name`, `TestModel5`\.`created`, `TestModel5`\.`updated`\s+'.
  1226. 'FROM\s+`test_model5` AS `TestModel5`\s+WHERE\s+'.
  1227. '(?:\()?\s*1 = 1\s*(?:\))?'.
  1228. '\s*$/', $result
  1229. );
  1230. }
  1231. /**
  1232. * testGenerateAssociationQueryHasManyWithConditions method
  1233. *
  1234. * @return void
  1235. */
  1236. public function testGenerateAssociationQueryHasManyWithConditions() {
  1237. $this->Model = new TestModel5();
  1238. $this->Model->schema();
  1239. $this->_buildRelatedModels($this->Model);
  1240. $binding = array('type' => 'hasMany', 'model' => 'TestModel6');
  1241. $queryData = array('conditions' => array('TestModel5.name !=' => 'mariano'));
  1242. $resultSet = null;
  1243. $null = null;
  1244. $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
  1245. $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
  1246. $this->assertRegExp('/^SELECT\s+`TestModel6`\.`id`, `TestModel6`\.`test_model5_id`, `TestModel6`\.`name`, `TestModel6`\.`created`, `TestModel6`\.`updated`\s+/', $result);
  1247. $this->assertRegExp('/\s+FROM\s+`test_model6` AS `TestModel6`\s+WHERE\s+/', $result);
  1248. $this->assertRegExp('/WHERE\s+(?:\()?`TestModel6`\.`test_model5_id`\s+=\s+\({\$__cakeID__\$}\)(?:\))?/', $result);
  1249. $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
  1250. $this->assertRegExp('/^SELECT\s+`TestModel5`\.`id`, `TestModel5`\.`test_model4_id`, `TestModel5`\.`name`, `TestModel5`\.`created`, `TestModel5`\.`updated`\s+/', $result);
  1251. $this->assertRegExp('/\s+FROM\s+`test_model5` AS `TestModel5`\s+WHERE\s+/', $result);
  1252. $this->assertRegExp('/\s+WHERE\s+(?:\()?`TestModel5`.`name`\s+!=\s+\'mariano\'(?:\))?\s*$/', $result);
  1253. }
  1254. /**
  1255. * testGenerateAssociationQueryHasManyWithOffsetAndLimit method
  1256. *
  1257. * @return void
  1258. */
  1259. public function testGenerateAssociationQueryHasManyWithOffsetAndLimit() {
  1260. $this->Model = new TestModel5();
  1261. $this->Model->schema();
  1262. $this->_buildRelatedModels($this->Model);
  1263. $__backup = $this->Model->hasMany['TestModel6'];
  1264. $this->Model->hasMany['TestModel6']['offset'] = 2;
  1265. $this->Model->hasMany['TestModel6']['limit'] = 5;
  1266. $binding = array('type' => 'hasMany', 'model' => 'TestModel6');
  1267. $queryData = array();
  1268. $resultSet = null;
  1269. $null = null;
  1270. $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
  1271. $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
  1272. $this->assertRegExp('/^SELECT\s+`TestModel6`\.`id`, `TestModel6`\.`test_model5_id`, `TestModel6`\.`name`, `TestModel6`\.`created`, `TestModel6`\.`updated`\s+/', $result);
  1273. $this->assertRegExp('/\s+FROM\s+`test_model6` AS `TestModel6`\s+WHERE\s+/', $result);
  1274. $this->assertRegExp('/WHERE\s+(?:\()?`TestModel6`\.`test_model5_id`\s+=\s+\({\$__cakeID__\$}\)(?:\))?/', $result);
  1275. $this->assertRegExp('/\s+LIMIT 2,\s*5\s*$/', $result);
  1276. $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
  1277. $this->assertRegExp('/^SELECT\s+`TestModel5`\.`id`, `TestModel5`\.`test_model4_id`, `TestModel5`\.`name`, `TestModel5`\.`created`, `TestModel5`\.`updated`\s+/', $result);
  1278. $this->assertRegExp('/\s+FROM\s+`test_model5` AS `TestModel5`\s+WHERE\s+/', $result);
  1279. $this->assertRegExp('/\s+WHERE\s+(?:\()?1\s+=\s+1(?:\))?\s*$/', $result);
  1280. $this->Model->hasMany['TestModel6'] = $__backup;
  1281. }
  1282. /**
  1283. * testGenerateAssociationQueryHasManyWithPageAndLimit method
  1284. *
  1285. * @return void
  1286. */
  1287. public function testGenerateAssociationQueryHasManyWithPageAndLimit() {
  1288. $this->Model = new TestModel5();
  1289. $this->Model->schema();
  1290. $this->_buildRelatedModels($this->Model);
  1291. $__backup = $this->Model->hasMany['TestModel6'];
  1292. $this->Model->hasMany['TestModel6']['page'] = 2;
  1293. $this->Model->hasMany['TestModel6']['limit'] = 5;
  1294. $binding = array('type' => 'hasMany', 'model' => 'TestModel6');
  1295. $queryData = array();
  1296. $resultSet = null;
  1297. $null = null;
  1298. $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
  1299. $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
  1300. $this->assertRegExp('/^SELECT\s+`TestModel6`\.`id`, `TestModel6`\.`test_model5_id`, `TestModel6`\.`name`, `TestModel6`\.`created`, `TestModel6`\.`updated`\s+/', $result);
  1301. $this->assertRegExp('/\s+FROM\s+`test_model6` AS `TestModel6`\s+WHERE\s+/', $result);
  1302. $this->assertRegExp('/WHERE\s+(?:\()?`TestModel6`\.`test_model5_id`\s+=\s+\({\$__cakeID__\$}\)(?:\))?/', $result);
  1303. $this->assertRegExp('/\s+LIMIT 5,\s*5\s*$/', $result);
  1304. $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
  1305. $this->assertRegExp('/^SELECT\s+`TestModel5`\.`id`, `TestModel5`\.`test_model4_id`, `TestModel5`\.`name`, `TestModel5`\.`created`, `TestModel5`\.`updated`\s+/', $result);
  1306. $this->assertRegExp('/\s+FROM\s+`test_model5` AS `TestModel5`\s+WHERE\s+/', $result);
  1307. $this->assertRegExp('/\s+WHERE\s+(?:\()?1\s+=\s+1(?:\))?\s*$/', $result);
  1308. $this->Model->hasMany['TestModel6'] = $__backup;
  1309. }
  1310. /**
  1311. * testGenerateAssociationQueryHasManyWithFields method
  1312. *
  1313. * @return void
  1314. */
  1315. public function testGenerateAssociationQueryHasManyWithFields() {
  1316. $this->Model = new TestModel5();
  1317. $this->Model->schema();
  1318. $this->_buildRelatedModels($this->Model);
  1319. $binding = array('type' => 'hasMany', 'model' => 'TestModel6');
  1320. $queryData = array('fields' => array('`TestModel5`.`name`'));
  1321. $resultSet = null;
  1322. $null = null;
  1323. $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
  1324. $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
  1325. $this->assertRegExp('/^SELECT\s+`TestModel6`\.`id`, `TestModel6`\.`test_model5_id`, `TestModel6`\.`name`, `TestModel6`\.`created`, `TestModel6`\.`updated`\s+/', $result);
  1326. $this->assertRegExp('/\s+FROM\s+`test_model6` AS `TestModel6`\s+WHERE\s+/', $result);
  1327. $this->assertRegExp('/WHERE\s+(?:\()?`TestModel6`\.`test_model5_id`\s+=\s+\({\$__cakeID__\$}\)(?:\))?/', $result);
  1328. $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
  1329. $this->assertRegExp('/^SELECT\s+`TestModel5`\.`name`, `TestModel5`\.`id`\s+/', $result);
  1330. $this->assertRegExp('/\s+FROM\s+`test_model5` AS `TestModel5`\s+WHERE\s+/', $result);
  1331. $this->assertRegExp('/\s+WHERE\s+(?:\()?1\s+=\s+1(?:\))?\s*$/', $result);
  1332. $binding = array('type' => 'hasMany', 'model' => 'TestModel6');
  1333. $queryData = array('fields' => array('`TestModel5`.`id`, `TestModel5`.`name`'));
  1334. $resultSet = null;
  1335. $null = null;
  1336. $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
  1337. $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
  1338. $this->assertRegExp('/^SELECT\s+`TestModel6`\.`id`, `TestModel6`\.`test_model5_id`, `TestModel6`\.`name`, `TestModel6`\.`created`, `TestModel6`\.`updated`\s+/', $result);
  1339. $this->assertRegExp('/\s+FROM\s+`test_model6` AS `TestModel6`\s+WHERE\s+/', $result);
  1340. $this->assertRegExp('/WHERE\s+(?:\()?`TestModel6`\.`test_model5_id`\s+=\s+\({\$__cakeID__\$}\)(?:\))?/', $result);
  1341. $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
  1342. $this->assertRegExp('/^SELECT\s+`TestModel5`\.`id`, `TestModel5`\.`name`\s+/', $result);
  1343. $this->assertRegExp('/\s+FROM\s+`test_model5` AS `TestModel5`\s+WHERE\s+/', $result);
  1344. $this->assertRegExp('/\s+WHERE\s+(?:\()?1\s+=\s+1(?:\))?\s*$/', $result);
  1345. $binding = array('type' => 'hasMany', 'model' => 'TestModel6');
  1346. $queryData = array('fields' => array('`TestModel5`.`name`', '`TestModel5`.`created`'));
  1347. $resultSet = null;
  1348. $null = null;
  1349. $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
  1350. $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
  1351. $this->assertRegExp('/^SELECT\s+`TestModel6`\.`id`, `TestModel6`\.`test_model5_id`, `TestModel6`\.`name`, `TestModel6`\.`created`, `TestModel6`\.`updated`\s+/', $result);
  1352. $this->assertRegExp('/\s+FROM\s+`test_model6` AS `TestModel6`\s+WHERE\s+/', $result);
  1353. $this->assertRegExp('/WHERE\s+(?:\()?`TestModel6`\.`test_model5_id`\s+=\s+\({\$__cakeID__\$}\)(?:\))?/', $result);
  1354. $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
  1355. $this->assertRegExp('/^SELECT\s+`TestModel5`\.`name`, `TestModel5`\.`created`, `TestModel5`\.`id`\s+/', $result);
  1356. $this->assertRegExp('/\s+FROM\s+`test_model5` AS `TestModel5`\s+WHERE\s+/', $result);
  1357. $this->assertRegExp('/\s+WHERE\s+(?:\()?1\s+=\s+1(?:\))?\s*$/', $result);
  1358. $this->Model->hasMany['TestModel6']['fields'] = array('name');
  1359. $binding = array('type' => 'hasMany', 'model' => 'TestModel6');
  1360. $queryData = array('fields' => array('`TestModel5`.`id`', '`TestModel5`.`name`'));
  1361. $resultSet = null;
  1362. $null = null;
  1363. $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
  1364. $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
  1365. $this->assertRegExp('/^SELECT\s+`TestModel6`\.`name`, `TestModel6`\.`test_model5_id`\s+/', $result);
  1366. $this->assertRegExp('/\s+FROM\s+`test_model6` AS `TestModel6`\s+WHERE\s+/', $result);
  1367. $this->assertRegExp('/WHERE\s+(?:\()?`TestModel6`\.`test_model5_id`\s+=\s+\({\$__cakeID__\$}\)(?:\))?/', $result);
  1368. $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
  1369. $this->assertRegExp('/^SELECT\s+`TestModel5`\.`id`, `TestModel5`\.`name`\s+/', $result);
  1370. $this->assertRegExp('/\s+FROM\s+`test_model5` AS `TestModel5`\s+WHERE\s+/', $result);
  1371. $this->assertRegExp('/\s+WHERE\s+(?:\()?1\s+=\s+1(?:\))?\s*$/', $result);
  1372. unset($this->Model->hasMany['TestModel6']['fields']);
  1373. $this->Model->hasMany['TestModel6']['fields'] = array('id', 'name');
  1374. $binding = array('type' => 'hasMany', 'model' => 'TestModel6');
  1375. $queryData = array('fields' => array('`TestModel5`.`id`', '`TestModel5`.`name`'));
  1376. $resultSet = null;
  1377. $null = null;
  1378. $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
  1379. $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
  1380. $this->assertRegExp('/^SELECT\s+`TestModel6`\.`id`, `TestModel6`\.`name`, `TestModel6`\.`test_model5_id`\s+/', $result);
  1381. $this->assertRegExp('/\s+FROM\s+`test_model6` AS `TestModel6`\s+WHERE\s+/', $result);
  1382. $this->assertRegExp('/WHERE\s+(?:\()?`TestModel6`\.`test_model5_id`\s+=\s+\({\$__cakeID__\$}\)(?:\))?/', $result);
  1383. $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
  1384. $this->assertRegExp('/^SELECT\s+`TestModel5`\.`id`, `TestModel5`\.`name`\s+/', $result);
  1385. $this->assertRegExp('/\s+FROM\s+`test_model5` AS `TestModel5`\s+WHERE\s+/', $result);
  1386. $this->assertRegExp('/\s+WHERE\s+(?:\()?1\s+=\s+1(?:\))?\s*$/', $result);
  1387. unset($this->Model->hasMany['TestModel6']['fields']);
  1388. $this->Model->hasMany['TestModel6']['fields'] = array('test_model5_id', 'name');
  1389. $binding = array('type' => 'hasMany', 'model' => 'TestModel6');
  1390. $queryData = array('fields' => array('`TestModel5`.`id`', '`TestModel5`.`name`'));
  1391. $resultSet = null;
  1392. $null = null;
  1393. $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
  1394. $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
  1395. $this->assertRegExp('/^SELECT\s+`TestModel6`\.`test_model5_id`, `TestModel6`\.`name`\s+/', $result);
  1396. $this->assertRegExp('/\s+FROM\s+`test_model6` AS `TestModel6`\s+WHERE\s+/', $result);
  1397. $this->assertRegExp('/WHERE\s+(?:\()?`TestModel6`\.`test_model5_id`\s+=\s+\({\$__cakeID__\$}\)(?:\))?/', $result);
  1398. $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
  1399. $this->assertRegExp('/^SELECT\s+`TestModel5`\.`id`, `TestModel5`\.`name`\s+/', $result);
  1400. $this->assertRegExp('/\s+FROM\s+`test_model5` AS `TestModel5`\s+WHERE\s+/', $result);
  1401. $this->assertRegExp('/\s+WHERE\s+(?:\()?1\s+=\s+1(?:\))?\s*$/', $result);
  1402. unset($this->Model->hasMany['TestModel6']['fields']);
  1403. }
  1404. /**
  1405. * test generateAssociationQuery with a hasMany and an aggregate function.
  1406. *
  1407. * @return void
  1408. */
  1409. public function testGenerateAssociationQueryHasManyAndAggregateFunction() {
  1410. $this->Model = new TestModel5();
  1411. $this->Model->schema();
  1412. $this->_buildRelatedModels($this->Model);
  1413. $binding = array('type' => 'hasMany', 'model' => 'TestModel6');
  1414. $queryData = array('fields' => array('MIN(`TestModel5`.`test_model4_id`)'));
  1415. $resultSet = null;
  1416. $null = null;
  1417. $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
  1418. $this->Model->recursive = 0;
  1419. $result = $this->Dbo->generateAssociationQuery($this->Model, $null, $params['type'], $params['assoc'], $params['assocData'], $queryData, false, $resultSet);
  1420. $this->assertRegExp('/^SELECT\s+MIN\(`TestModel5`\.`test_model4_id`\)\s+FROM/', $result);
  1421. }
  1422. /**
  1423. * testGenerateAssociationQueryHasAndBelongsToMany method
  1424. *
  1425. * @return void
  1426. */
  1427. public function testGenerateAssociationQueryHasAndBelongsToMany() {
  1428. $this->Model = new TestModel4();
  1429. $this->Model->schema();
  1430. $this->_buildRelatedModels($this->Model);
  1431. $binding = array('type' => 'hasAndBelongsToMany', 'model' => 'TestModel7');
  1432. $queryData = array();
  1433. $resultSet = null;
  1434. $null = null;
  1435. $params = $this->_prepareAssociationQuery($this->Model, $queryData, $binding);
  1436. $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
  1437. $assocTable = $this->Dbo->fullTableName($this->Model->TestModel4TestModel7, false);
  1438. $this->assertRegExp('/^SELECT\s+`TestModel7`\.`id`, `TestModel7`\.`name`, `TestModel7`\.`created`, `TestModel7`\.`updated`, `TestModel4TestModel7`\.`test_model4_id`, `TestModel4TestModel7`\.`test_model7_id`\s+/', $result);
  1439. $this->assertRegExp('/\s+FROM\s+`test_model7` AS `TestModel7`\s+JOIN\s+`' . $assocTable . '`/', $result);
  1440. $this->assertRegExp('/\s+ON\s+\(`TestModel4TestModel7`\.`test_model4_id`\s+=\s+{\$__cakeID__\$}\s+AND/', $result);
  1441. $this->assertRegExp('/\s+AND\s+`TestModel4TestModel7`\.`test_model7_id`\s+=\s+`TestModel7`\.`id`\)/', $result);
  1442. $this->assertRegExp('/WHERE\s+(?:\()?1 = 1(?:\))?\s*$/', $result);
  1443. $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
  1444. $this->assertRegExp('/^SELECT\s+`TestModel4`\.`id`, `TestModel4`\.`name`, `TestModel4`\.`created`, `TestModel4`\.`updated`\s+/', $result);
  1445. $this->assertRegExp('/\s+FROM\s+`test_model4` AS `TestModel4`\s+WHERE/', $result);
  1446. $this->assertRegExp('/\s+WHERE\s+(?:\()?1 = 1(?:\))?\s*$/', $result);
  1447. }
  1448. /**
  1449. * testGenerateAssociationQueryHasAndBelongsToManyWithConditions method
  1450. *
  1451. * @return void
  1452. */
  1453. public function testGenerateAssociationQueryHasAndBelongsToManyWithConditions() {
  1454. $this->Model = new TestModel4();
  1455. $this->Model->schema();
  1456. $this->_buildRelatedModels($this->Model);
  1457. $binding = array('type' => 'hasAndBelongsToMany', 'model' => 'TestModel7');
  1458. $queryData = array('conditions' => array('TestModel4.name !=' => 'mariano'));
  1459. $resultSet = null;
  1460. $null = null;
  1461. $params = $this->_prepareAssociationQuery($this->Model, $queryData, $binding);
  1462. $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
  1463. $this->assertRegExp('/^SELECT\s+`TestModel7`\.`id`, `TestModel7`\.`name`, `TestModel7`\.`created`, `TestModel7`\.`updated`, `TestModel4TestModel7`\.`test_model4_id`, `TestModel4TestModel7`\.`test_model7_id`\s+/', $result);
  1464. $this->assertRegExp('/\s+FROM\s+`test_model7`\s+AS\s+`TestModel7`\s+JOIN\s+`test_model4_test_model7`\s+AS\s+`TestModel4TestModel7`/', $result);
  1465. $this->assertRegExp('/\s+ON\s+\(`TestModel4TestModel7`\.`test_model4_id`\s+=\s+{\$__cakeID__\$}/', $result);
  1466. $this->assertRegExp('/\s+AND\s+`TestModel4TestModel7`\.`test_model7_id`\s+=\s+`TestModel7`\.`id`\)\s+WHERE\s+/', $result);
  1467. $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
  1468. $this->assertRegExp('/^SELECT\s+`TestModel4`\.`id`, `TestModel4`\.`name`, `TestModel4`\.`created`, `TestModel4`\.`updated`\s+/', $result);
  1469. $this->assertRegExp('/\s+FROM\s+`test_model4` AS `TestModel4`\s+WHERE\s+(?:\()?`TestModel4`.`name`\s+!=\s+\'mariano\'(?:\))?\s*$/', $result);
  1470. }
  1471. /**
  1472. * testGenerateAssociationQueryHasAndBelongsToManyWithOffsetAndLimit method
  1473. *
  1474. * @return void
  1475. */
  1476. public function testGenerateAssociationQueryHasAndBelongsToManyWithOffsetAndLimit() {
  1477. $this->Model = new TestModel4();
  1478. $this->Model->schema();
  1479. $this->_buildRelatedModels($this->Model);
  1480. $__backup = $this->Model->hasAndBelongsToMany['TestModel7'];
  1481. $this->Model->hasAndBelongsToMany['TestModel7']['offset'] = 2;
  1482. $this->Model->hasAndBelongsToMany['TestModel7']['limit'] = 5;
  1483. $binding = array('type' => 'hasAndBelongsToMany', 'model' => 'TestModel7');
  1484. $queryData = array();
  1485. $resultSet = null;
  1486. $null = null;
  1487. $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
  1488. $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
  1489. $this->assertRegExp('/^SELECT\s+`TestModel7`\.`id`, `TestModel7`\.`name`, `TestModel7`\.`created`, `TestModel7`\.`updated`, `TestModel4TestModel7`\.`test_model4_id`, `TestModel4TestModel7`\.`test_model7_id`\s+/', $result);
  1490. $this->assertRegExp('/\s+FROM\s+`test_model7`\s+AS\s+`TestModel7`\s+JOIN\s+`test_model4_test_model7`\s+AS\s+`TestModel4TestModel7`/', $result);
  1491. $this->assertRegExp('/\s+ON\s+\(`TestModel4TestModel7`\.`test_model4_id`\s+=\s+{\$__cakeID__\$}\s+/', $result);
  1492. $this->assertRegExp('/\s+AND\s+`TestModel4TestModel7`\.`test_model7_id`\s+=\s+`TestModel7`\.`id`\)\s+WHERE\s+/', $result);
  1493. $this->assertRegExp('/\s+(?:\()?1\s+=\s+1(?:\))?\s*\s+LIMIT 2,\s*5\s*$/', $result);
  1494. $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
  1495. $this->assertRegExp('/^SELECT\s+`TestModel4`\.`id`, `TestModel4`\.`name`, `TestModel4`\.`created`, `TestModel4`\.`updated`\s+/', $result);
  1496. $this->assertRegExp('/\s+FROM\s+`test_model4` AS `TestModel4`\s+WHERE\s+(?:\()?1\s+=\s+1(?:\))?\s*$/', $result);
  1497. $this->Model->hasAndBelongsToMany['TestModel7'] = $__backup;
  1498. }
  1499. /**
  1500. * testGenerateAssociationQueryHasAndBelongsToManyWithPageAndLimit method
  1501. *
  1502. * @return void
  1503. */
  1504. public function testGenerateAssociationQueryHasAndBelongsToManyWithPageAndLimit() {
  1505. $this->Model = new TestModel4();
  1506. $this->Model->schema();
  1507. $this->_buildRelatedModels($this->Model);
  1508. $__backup = $this->Model->hasAndBelongsToMany['TestModel7'];
  1509. $this->Model->hasAndBelongsToMany['TestModel7']['page'] = 2;
  1510. $this->Model->hasAndBelongsToMany['TestModel7']['limit'] = 5;
  1511. $binding = array('type' => 'hasAndBelongsToMany', 'model' => 'TestModel7');
  1512. $queryData = array();
  1513. $resultSet = null;
  1514. $null = null;
  1515. $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding);
  1516. $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
  1517. $this->assertRegExp('/^SELECT\s+`TestModel7`\.`id`, `TestModel7`\.`name`, `TestModel7`\.`created`, `TestModel7`\.`updated`, `TestModel4TestModel7`\.`test_model4_id`, `TestModel4TestModel7`\.`test_model7_id`\s+/', $result);
  1518. $this->assertRegExp('/\s+FROM\s+`test_model7`\s+AS\s+`TestModel7`\s+JOIN\s+`test_model4_test_model7`\s+AS\s+`TestModel4TestModel7`/', $result);
  1519. $this->assertRegExp('/\s+ON\s+\(`TestModel4TestModel7`\.`test_model4_id`\s+=\s+{\$__cakeID__\$}/', $result);
  1520. $this->assertRegExp('/\s+AND\s+`TestModel4TestModel7`\.`test_model7_id`\s+=\s+`TestModel7`\.`id`\)\s+WHERE\s+/', $result);
  1521. $this->assertRegExp('/\s+(?:\()?1\s+=\s+1(?:\))?\s*\s+LIMIT 5,\s*5\s*$/', $result);
  1522. $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null);
  1523. $this->assertRegExp('/^SELECT\s+`TestModel4`\.`id`, `TestModel4`\.`name`, `TestModel4`\.`created`, `TestModel4`\.`updated`\s+/', $result);
  1524. $this->assertRegExp('/\s+FROM\s+`test_model4` AS `TestModel4`\s+WHERE\s+(?:\()?1\s+=\s+1(?:\))?\s*$/', $result);
  1525. $this->Model->hasAndBelongsToMany['TestModel7'] = $__backup;
  1526. }
  1527. /**
  1528. * testSelectDistict method
  1529. *
  1530. * @return void
  1531. */
  1532. public function testSelectDistict() {
  1533. $this->Model = new TestModel4();
  1534. $result = $this->Dbo->fields($this->Model, 'Vendor', "DISTINCT Vendor.id, Vendor.name");
  1535. $expected = array('DISTINCT `Vendor`.`id`', '`Vendor`.`name`');
  1536. $this->assertEquals($expected, $result);
  1537. }
  1538. /**
  1539. * testStringConditionsParsing method
  1540. *
  1541. * @return void
  1542. */
  1543. public function testStringConditionsParsing() {
  1544. $result = $this->Dbo->conditions("ProjectBid.project_id = Project.id");
  1545. $expected = " WHERE `ProjectBid`.`project_id` = `Project`.`id`";
  1546. $this->assertEquals($expected, $result);
  1547. $result = $this->Dbo->conditions("Candy.name LIKE 'a' AND HardCandy.name LIKE 'c'");
  1548. $expected = " WHERE `Candy`.`name` LIKE 'a' AND `HardCandy`.`name` LIKE 'c'";
  1549. $this->assertEquals($expected, $result);
  1550. $result = $this->Dbo->conditions("HardCandy.name LIKE 'a' AND Candy.name LIKE 'c'");
  1551. $expected = " WHERE `HardCandy`.`name` LIKE 'a' AND `Candy`.`name` LIKE 'c'";
  1552. $this->assertEquals($expected, $result);
  1553. $result = $this->Dbo->conditions("Post.title = '1.1'");
  1554. $expected = " WHERE `Post`.`title` = '1.1'";
  1555. $this->assertEquals($expected, $result);
  1556. $result = $this->Dbo->conditions("User.id != 0 AND User.user LIKE '%arr%'");
  1557. $expected = " WHERE `User`.`id` != 0 AND `User`.`user` LIKE '%arr%'";
  1558. $this->assertEquals($expected, $result);
  1559. $result = $this->Dbo->conditions("SUM(Post.comments_count) > 500");
  1560. $expected = " WHERE SUM(`Post`.`comments_count`) > 500";
  1561. $this->assertEquals($expected, $result);
  1562. $result = $this->Dbo->conditions("(Post.created < '" . date('Y-m-d H:i:s') . "') GROUP BY YEAR(Post.created), MONTH(Post.created)");
  1563. $expected = " WHERE (`Post`.`created` < '" . date('Y-m-d H:i:s') . "') GROUP BY YEAR(`Post`.`created`), MONTH(`Post`.`created`)";
  1564. $this->assertEquals($expected, $result);
  1565. $result = $this->Dbo->conditions("score BETWEEN 90.1 AND 95.7");
  1566. $expected = " WHERE score BETWEEN 90.1 AND 95.7";
  1567. $this->assertEquals($expected, $result);
  1568. $result = $this->Dbo->conditions(array('score' => array(2 => 1, 2, 10)));
  1569. $expected = " WHERE score IN (1, 2, 10)";
  1570. $this->assertEquals($expected, $result);
  1571. $result = $this->Dbo->conditions("Aro.rght = Aro.lft + 1.1");
  1572. $expected = " WHERE `Aro`.`rght` = `Aro`.`lft` + 1.1";
  1573. $this->assertEquals($expected, $result);
  1574. $result = $this->Dbo->conditions("(Post.created < '" . date('Y-m-d H:i:s') . "') GROUP BY YEAR(Post.created), MONTH(Post.created)");
  1575. $expected = " WHERE (`Post`.`created` < '" . date('Y-m-d H:i:s') . "') GROUP BY YEAR(`Post`.`created`), MONTH(`Post`.`created`)";
  1576. $this->assertEquals($expected, $result);
  1577. $result = $this->Dbo->conditions('Sportstaette.sportstaette LIKE "%ru%" AND Sportstaette.sportstaettenart_id = 2');
  1578. $expected = ' WHERE `Sportstaette`.`sportstaette` LIKE "%ru%" AND `Sportstaette`.`sportstaettenart_id` = 2';
  1579. $this->assertRegExp('/\s*WHERE\s+`Sportstaette`\.`sportstaette`\s+LIKE\s+"%ru%"\s+AND\s+`Sports/', $result);
  1580. $this->assertEquals($expected, $result);
  1581. $result = $this->Dbo->conditions('Sportstaette.sportstaettenart_id = 2 AND Sportstaette.sportstaette LIKE "%ru%"');
  1582. $expected = ' WHERE `Sportstaette`.`sportstaettenart_id` = 2 AND `Sportstaette`.`sportstaette` LIKE "%ru%"';
  1583. $this->assertEquals($expected, $result);
  1584. $result = $this->Dbo->conditions('SUM(Post.comments_count) > 500 AND NOT Post.title IS NULL AND NOT Post.extended_title IS NULL');
  1585. $expected = ' WHERE SUM(`Post`.`comments_count`) > 500 AND NOT `Post`.`title` IS NULL AND NOT `Post`.`extended_title` IS NULL';
  1586. $this->assertEquals($expected, $result);
  1587. $result = $this->Dbo->conditions('NOT Post.title IS NULL AND NOT Post.extended_title IS NULL AND SUM(Post.comments_count) > 500');
  1588. $expected = ' WHERE NOT `Post`.`title` IS NULL AND NOT `Post`.`extended_title` IS NULL AND SUM(`Post`.`comments_count`) > 500';
  1589. $this->assertEquals($expected, $result);
  1590. $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');
  1591. $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';
  1592. $this->assertEquals($expected, $result);
  1593. $result = $this->Dbo->conditions('NOT Post.title_extended IS NULL AND NOT Post.title IS NULL AND Post.title_extended != Post.title');
  1594. $expected = ' WHERE NOT `Post`.`title_extended` IS NULL AND NOT `Post`.`title` IS NULL AND `Post`.`title_extended` != `Post`.`title`';
  1595. $this->assertEquals($expected, $result);
  1596. $result = $this->Dbo->conditions("Comment.id = 'a'");
  1597. $expected = " WHERE `Comment`.`id` = 'a'";
  1598. $this->assertEquals($expected, $result);
  1599. $result = $this->Dbo->conditions("lower(Article.title) LIKE 'a%'");
  1600. $expected = " WHERE lower(`Article`.`title`) LIKE 'a%'";
  1601. $this->assertEquals($expected, $result);
  1602. $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))');
  1603. $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))';
  1604. $this->assertEquals($expected, $result);
  1605. $result = $this->Dbo->conditions('DATEDIFF(NOW(),Article.published) < 1 && Article.live=1');
  1606. $expected = " WHERE DATEDIFF(NOW(),`Article`.`published`) < 1 && `Article`.`live`=1";
  1607. $this->assertEquals($expected, $result);
  1608. $result = $this->Dbo->conditions('file = "index.html"');
  1609. $expected = ' WHERE file = "index.html"';
  1610. $this->assertEquals($expected, $result);
  1611. $result = $this->Dbo->conditions("file = 'index.html'");
  1612. $expected = " WHERE file = 'index.html'";
  1613. $this->assertEquals($expected, $result);
  1614. $letter = $letter = 'd.a';
  1615. $conditions = array('Company.name like ' => $letter . '%');
  1616. $result = $this->Dbo->conditions($conditions);
  1617. $expected = " WHERE `Company`.`name` like 'd.a%'";
  1618. $this->assertEquals($expected, $result);
  1619. $conditions = array('Artist.name' => 'JUDY and MARY');
  1620. $result = $this->Dbo->conditions($conditions);
  1621. $expected = " WHERE `Artist`.`name` = 'JUDY and MARY'";
  1622. $this->assertEquals($expected, $result);
  1623. $conditions = array('Artist.name' => 'JUDY AND MARY');
  1624. $result = $this->Dbo->conditions($conditions);
  1625. $expected = " WHERE `Artist`.`name` = 'JUDY AND MARY'";
  1626. $this->assertEquals($expected, $result);
  1627. $conditions = array('Company.name similar to ' => 'a word');
  1628. $result = $this->Dbo->conditions($conditions);
  1629. $expected = " WHERE `Company`.`name` similar to 'a word'";
  1630. $this->assertEquals($expected, $result);
  1631. }
  1632. /**
  1633. * testQuotesInStringConditions method
  1634. *
  1635. * @return void
  1636. */
  1637. public function testQuotesInStringConditions() {
  1638. $result = $this->Dbo->conditions('Member.email = \'mariano@cricava.com\'');
  1639. $expected = ' WHERE `Member`.`email` = \'mariano@cricava.com\'';
  1640. $this->assertEquals($expected, $result);
  1641. $result = $this->Dbo->conditions('Member.email = "mariano@cricava.com"');
  1642. $expected = ' WHERE `Member`.`email` = "mariano@cricava.com"';
  1643. $this->assertEquals($expected, $result);
  1644. $result = $this->Dbo->conditions('Member.email = \'mariano@cricava.com\' AND Member.user LIKE \'mariano.iglesias%\'');
  1645. $expected = ' WHERE `Member`.`email` = \'mariano@cricava.com\' AND `Member`.`user` LIKE \'mariano.iglesias%\'';
  1646. $this->assertEquals($expected, $result);
  1647. $result = $this->Dbo->conditions('Member.email = "mariano@cricava.com" AND Member.user LIKE "mariano.iglesias%"');
  1648. $expected = ' WHERE `Member`.`email` = "mariano@cricava.com" AND `Member`.`user` LIKE "mariano.iglesias%"';
  1649. $this->assertEquals($expected, $result);
  1650. }
  1651. /**
  1652. * testParenthesisInStringConditions method
  1653. *
  1654. * @return void
  1655. */
  1656. public function testParenthesisInStringConditions() {
  1657. $result = $this->Dbo->conditions('Member.name = \'(lu\'');
  1658. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(lu\'$/', $result);
  1659. $result = $this->Dbo->conditions('Member.name = \')lu\'');
  1660. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\)lu\'$/', $result);
  1661. $result = $this->Dbo->conditions('Member.name = \'va(lu\'');
  1662. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'va\(lu\'$/', $result);
  1663. $result = $this->Dbo->conditions('Member.name = \'va)lu\'');
  1664. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'va\)lu\'$/', $result);
  1665. $result = $this->Dbo->conditions('Member.name = \'va(lu)\'');
  1666. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'va\(lu\)\'$/', $result);
  1667. $result = $this->Dbo->conditions('Member.name = \'va(lu)e\'');
  1668. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'va\(lu\)e\'$/', $result);
  1669. $result = $this->Dbo->conditions('Member.name = \'(mariano)\'');
  1670. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(mariano\)\'$/', $result);
  1671. $result = $this->Dbo->conditions('Member.name = \'(mariano)iglesias\'');
  1672. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(mariano\)iglesias\'$/', $result);
  1673. $result = $this->Dbo->conditions('Member.name = \'(mariano) iglesias\'');
  1674. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(mariano\) iglesias\'$/', $result);
  1675. $result = $this->Dbo->conditions('Member.name = \'(mariano word) iglesias\'');
  1676. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(mariano word\) iglesias\'$/', $result);
  1677. $result = $this->Dbo->conditions('Member.name = \'(mariano.iglesias)\'');
  1678. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(mariano.iglesias\)\'$/', $result);
  1679. $result = $this->Dbo->conditions('Member.name = \'Mariano Iglesias (mariano.iglesias)\'');
  1680. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'Mariano Iglesias \(mariano.iglesias\)\'$/', $result);
  1681. $result = $this->Dbo->conditions('Member.name = \'Mariano Iglesias (mariano.iglesias) CakePHP\'');
  1682. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'Mariano Iglesias \(mariano.iglesias\) CakePHP\'$/', $result);
  1683. $result = $this->Dbo->conditions('Member.name = \'(mariano.iglesias) CakePHP\'');
  1684. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(mariano.iglesias\) CakePHP\'$/', $result);
  1685. }
  1686. /**
  1687. * testParenthesisInArrayConditions method
  1688. *
  1689. * @return void
  1690. */
  1691. public function testParenthesisInArrayConditions() {
  1692. $result = $this->Dbo->conditions(array('Member.name' => '(lu'));
  1693. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(lu\'$/', $result);
  1694. $result = $this->Dbo->conditions(array('Member.name' => ')lu'));
  1695. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\)lu\'$/', $result);
  1696. $result = $this->Dbo->conditions(array('Member.name' => 'va(lu'));
  1697. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'va\(lu\'$/', $result);
  1698. $result = $this->Dbo->conditions(array('Member.name' => 'va)lu'));
  1699. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'va\)lu\'$/', $result);
  1700. $result = $this->Dbo->conditions(array('Member.name' => 'va(lu)'));
  1701. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'va\(lu\)\'$/', $result);
  1702. $result = $this->Dbo->conditions(array('Member.name' => 'va(lu)e'));
  1703. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'va\(lu\)e\'$/', $result);
  1704. $result = $this->Dbo->conditions(array('Member.name' => '(mariano)'));
  1705. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(mariano\)\'$/', $result);
  1706. $result = $this->Dbo->conditions(array('Member.name' => '(mariano)iglesias'));
  1707. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(mariano\)iglesias\'$/', $result);
  1708. $result = $this->Dbo->conditions(array('Member.name' => '(mariano) iglesias'));
  1709. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(mariano\) iglesias\'$/', $result);
  1710. $result = $this->Dbo->conditions(array('Member.name' => '(mariano word) iglesias'));
  1711. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(mariano word\) iglesias\'$/', $result);
  1712. $result = $this->Dbo->conditions(array('Member.name' => '(mariano.iglesias)'));
  1713. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(mariano.iglesias\)\'$/', $result);
  1714. $result = $this->Dbo->conditions(array('Member.name' => 'Mariano Iglesias (mariano.iglesias)'));
  1715. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'Mariano Iglesias \(mariano.iglesias\)\'$/', $result);
  1716. $result = $this->Dbo->conditions(array('Member.name' => 'Mariano Iglesias (mariano.iglesias) CakePHP'));
  1717. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'Mariano Iglesias \(mariano.iglesias\) CakePHP\'$/', $result);
  1718. $result = $this->Dbo->conditions(array('Member.name' => '(mariano.iglesias) CakePHP'));
  1719. $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(mariano.iglesias\) CakePHP\'$/', $result);
  1720. }
  1721. /**
  1722. * testArrayConditionsParsing method
  1723. *
  1724. * @return void
  1725. */
  1726. public function testArrayConditionsParsing() {
  1727. $this->loadFixtures('Post', 'Author');
  1728. $result = $this->Dbo->conditions(array('Stereo.type' => 'in dash speakers'));
  1729. $this->assertRegExp("/^\s+WHERE\s+`Stereo`.`type`\s+=\s+'in dash speakers'/", $result);
  1730. $result = $this->Dbo->conditions(array('Candy.name LIKE' => 'a', 'HardCandy.name LIKE' => 'c'));
  1731. $this->assertRegExp("/^\s+WHERE\s+`Candy`.`name` LIKE\s+'a'\s+AND\s+`HardCandy`.`name`\s+LIKE\s+'c'/", $result);
  1732. $result = $this->Dbo->conditions(array('HardCandy.name LIKE' => 'a', 'Candy.name LIKE' => 'c'));
  1733. $expected = " WHERE `HardCandy`.`name` LIKE 'a' AND `Candy`.`name` LIKE 'c'";
  1734. $this->assertEquals($expected, $result);
  1735. $result = $this->Dbo->conditions(array('HardCandy.name LIKE' => 'a%', 'Candy.name LIKE' => '%c%'));
  1736. $expected = " WHERE `HardCandy`.`name` LIKE 'a%' AND `Candy`.`name` LIKE '%c%'";
  1737. $this->assertEquals($expected, $result);
  1738. $result = $this->Dbo->conditions(array('HardCandy.name LIKE' => 'to be or%', 'Candy.name LIKE' => '%not to be%'));
  1739. $expected = " WHERE `HardCandy`.`name` LIKE 'to be or%' AND `Candy`.`name` LIKE '%not to be%'";
  1740. $this->assertEquals($expected, $result);
  1741. $result = $this->Dbo->conditions(array('score BETWEEN ? AND ?' => array(90.1, 95.7)));
  1742. $expected = " WHERE `score` BETWEEN 90.1 AND 95.7";
  1743. $this->assertEquals($expected, $result);
  1744. $result = $this->Dbo->conditions(array('Post.title' => 1.1));
  1745. $expected = " WHERE `Post`.`title` = 1.1";
  1746. $this->assertEquals($expected, $result);
  1747. $result = $this->Dbo->conditions(array('Post.title' => 1.1), true, true, new Post());
  1748. $expected = " WHERE `Post`.`title` = '1.1'";
  1749. $this->assertEquals($expected, $result);
  1750. $result = $this->Dbo->conditions(array('SUM(Post.comments_count) >' => '500'));
  1751. $expected = " WHERE SUM(`Post`.`comments_count`) > '500'";
  1752. $this->assertEquals($expected, $result);
  1753. $result = $this->Dbo->conditions(array('MAX(Post.rating) >' => '50'));
  1754. $expected = " WHERE MAX(`Post`.`rating`) > '50'";
  1755. $this->assertEquals($expected, $result);
  1756. $result = $this->Dbo->conditions(array('lower(Article.title)' => 'secrets'));
  1757. $expected = " WHERE lower(`Article`.`title`) = 'secrets'";
  1758. $this->assertEquals($expected, $result);
  1759. $result = $this->Dbo->conditions(array('title LIKE' => '%hello'));
  1760. $expected = " WHERE `title` LIKE '%hello'";
  1761. $this->assertEquals($expected, $result);
  1762. $result = $this->Dbo->conditions(array('Post.name' => 'mad(g)ik'));
  1763. $expected = " WHERE `Post`.`name` = 'mad(g)ik'";
  1764. $this->assertEquals($expected, $result);
  1765. $result = $this->Dbo->conditions(array('score' => array(1, 2, 10)));
  1766. $expected = " WHERE score IN (1, 2, 10)";
  1767. $this->assertEquals($expected, $result);
  1768. $result = $this->Dbo->conditions(array('score' => array()));
  1769. $expected = " WHERE `score` IS NULL";
  1770. $this->assertEquals($expected, $result);
  1771. $result = $this->Dbo->conditions(array('score !=' => array()));
  1772. $expected = " WHERE `score` IS NOT NULL";
  1773. $this->assertEquals($expected, $result);
  1774. $result = $this->Dbo->conditions(array('score !=' => '20'));
  1775. $expected = " WHERE `score` != '20'";
  1776. $this->assertEquals($expected, $result);
  1777. $result = $this->Dbo->conditions(array('score >' => '20'));
  1778. $expected = " WHERE `score` > '20'";
  1779. $this->assertEquals($expected, $result);
  1780. $result = $this->Dbo->conditions(array('client_id >' => '20'), true, true, new TestModel());
  1781. $expected = " WHERE `client_id` > 20";
  1782. $this->assertEquals($expected, $result);
  1783. $result = $this->Dbo->conditions(array('OR' => array(
  1784. array('User.user' => 'mariano'),
  1785. array('User.user' => 'nate')
  1786. )));
  1787. $expected = " WHERE ((`User`.`user` = 'mariano') OR (`User`.`user` = 'nate'))";
  1788. $this->assertEquals($expected, $result);
  1789. $result = $this->Dbo->conditions(array('or' => array(
  1790. 'score BETWEEN ? AND ?' => array('4', '5'), 'rating >' => '20'
  1791. )));
  1792. $expected = " WHERE ((`score` BETWEEN '4' AND '5') OR (`rating` > '20'))";
  1793. $this->assertEquals($expected, $result);
  1794. $result = $this->Dbo->conditions(array('or' => array(
  1795. 'score BETWEEN ? AND ?' => array('4', '5'), array('score >' => '20')
  1796. )));
  1797. $expected = " WHERE ((`score` BETWEEN '4' AND '5') OR (`score` > '20'))";
  1798. $this->assertEquals($expected, $result);
  1799. $result = $this->Dbo->conditions(array('and' => array(
  1800. 'score BETWEEN ? AND ?' => array('4', '5'), array('score >' => '20')
  1801. )));
  1802. $expected = " WHERE ((`score` BETWEEN '4' AND '5') AND (`score` > '20'))";
  1803. $this->assertEquals($expected, $result);
  1804. $result = $this->Dbo->conditions(array(
  1805. 'published' => 1, 'or' => array('score >' => '2', array('score >' => '20'))
  1806. ));
  1807. $expected = " WHERE `published` = 1 AND ((`score` > '2') OR (`score` > '20'))";
  1808. $this->assertEquals($expected, $result);
  1809. $result = $this->Dbo->conditions(array(array('Project.removed' => false)));
  1810. $expected = " WHERE `Project`.`removed` = '0'";
  1811. $this->assertEquals($expected, $result);
  1812. $result = $this->Dbo->conditions(array(array('Project.removed' => true)));
  1813. $expected = " WHERE `Project`.`removed` = '1'";
  1814. $this->assertEquals($expected, $result);
  1815. $result = $this->Dbo->conditions(array(array('Project.removed' => null)));
  1816. $expected = " WHERE `Project`.`removed` IS NULL";
  1817. $this->assertEquals($expected, $result);
  1818. $result = $this->Dbo->conditions(array(array('Project.removed !=' => null)));
  1819. $expected = " WHERE `Project`.`removed` IS NOT NULL";
  1820. $this->assertEquals($expected, $result);
  1821. $result = $this->Dbo->conditions(array('(Usergroup.permissions) & 4' => 4));
  1822. $expected = " WHERE (`Usergroup`.`permissions`) & 4 = 4";
  1823. $this->assertEquals($expected, $result);
  1824. $result = $this->Dbo->conditions(array('((Usergroup.permissions) & 4)' => 4));
  1825. $expected = " WHERE ((`Usergroup`.`permissions`) & 4) = 4";
  1826. $this->assertEquals($expected, $result);
  1827. $result = $this->Dbo->conditions(array('Post.modified >=' => 'DATE_SUB(NOW(), INTERVAL 7 DAY)'));
  1828. $expected = " WHERE `Post`.`modified` >= 'DATE_SUB(NOW(), INTERVAL 7 DAY)'";
  1829. $this->assertEquals($expected, $result);
  1830. $result = $this->Dbo->conditions(array('Post.modified >= DATE_SUB(NOW(), INTERVAL 7 DAY)'));
  1831. $expected = " WHERE `Post`.`modified` >= DATE_SUB(NOW(), INTERVAL 7 DAY)";
  1832. $this->assertEquals($expected, $result);
  1833. $result = $this->Dbo->conditions(array(
  1834. 'NOT' => array('Course.id' => null, 'Course.vet' => 'N', 'level_of_education_id' => array(912,999)),
  1835. 'Enrollment.yearcompleted >' => '0')
  1836. );
  1837. $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);
  1838. $result = $this->Dbo->conditions(array('id <>' => '8'));
  1839. $this->assertRegExp('/^\s*WHERE\s+`id`\s+<>\s+\'8\'\s*$/', $result);
  1840. $result = $this->Dbo->conditions(array('TestModel.field =' => 'gribe$@()lu'));
  1841. $expected = " WHERE `TestModel`.`field` = 'gribe$@()lu'";
  1842. $this->assertEquals($expected, $result);
  1843. $conditions['NOT'] = array('Listing.expiration BETWEEN ? AND ?' => array("1", "100"));
  1844. $conditions[0]['OR'] = array(
  1845. "Listing.title LIKE" => "%term%",
  1846. "Listing.description LIKE" => "%term%"
  1847. );
  1848. $conditions[1]['OR'] = array(
  1849. "Listing.title LIKE" => "%term_2%",
  1850. "Listing.description LIKE" => "%term_2%"
  1851. );
  1852. $result = $this->Dbo->conditions($conditions);
  1853. $expected = " WHERE NOT (`Listing`.`expiration` BETWEEN '1' AND '100') AND" .
  1854. " ((`Listing`.`title` LIKE '%term%') OR (`Listing`.`description` LIKE '%term%')) AND" .
  1855. " ((`Listing`.`title` LIKE '%term_2%') OR (`Listing`.`description` LIKE '%term_2%'))";
  1856. $this->assertEquals($expected, $result);
  1857. $result = $this->Dbo->conditions(array('MD5(CONCAT(Reg.email,Reg.id))' => 'blah'));
  1858. $expected = " WHERE MD5(CONCAT(`Reg`.`email`,`Reg`.`id`)) = 'blah'";
  1859. $this->assertEquals($expected, $result);
  1860. $result = $this->Dbo->conditions(array(
  1861. 'MD5(CONCAT(Reg.email,Reg.id))' => array('blah', 'blahblah')
  1862. ));
  1863. $expected = " WHERE MD5(CONCAT(`Reg`.`email`,`Reg`.`id`)) IN ('blah', 'blahblah')";
  1864. $this->assertEquals($expected, $result);
  1865. $conditions = array('id' => array(2, 5, 6, 9, 12, 45, 78, 43, 76));
  1866. $result = $this->Dbo->conditions($conditions);
  1867. $expected = " WHERE id IN (2, 5, 6, 9, 12, 45, 78, 43, 76)";
  1868. $this->assertEquals($expected, $result);
  1869. $conditions = array('title' => 'user(s)');
  1870. $result = $this->Dbo->conditions($conditions);
  1871. $expected = " WHERE `title` = 'user(s)'";
  1872. $this->assertEquals($expected, $result);
  1873. $conditions = array('title' => 'user(s) data');
  1874. $result = $this->Dbo->conditions($conditions);
  1875. $expected = " WHERE `title` = 'user(s) data'";
  1876. $this->assertEquals($expected, $result);
  1877. $conditions = array('title' => 'user(s,arg) data');
  1878. $result = $this->Dbo->conditions($conditions);
  1879. $expected = " WHERE `title` = 'user(s,arg) data'";
  1880. $this->assertEquals($expected, $result);
  1881. $result = $this->Dbo->conditions(array("Book.book_name" => 'Java(TM)'));
  1882. $expected = " WHERE `Book`.`book_name` = 'Java(TM)'";
  1883. $this->assertEquals($expected, $result);
  1884. $result = $this->Dbo->conditions(array("Book.book_name" => 'Java(TM) '));
  1885. $expected = " WHERE `Book`.`book_name` = 'Java(TM) '";
  1886. $this->assertEquals($expected, $result);
  1887. $result = $this->Dbo->conditions(array("Book.id" => 0));
  1888. $expected = " WHERE `Book`.`id` = 0";
  1889. $this->assertEquals($expected, $result);
  1890. $result = $this->Dbo->conditions(array("Book.id" => null));
  1891. $expected = " WHERE `Book`.`id` IS NULL";
  1892. $this->assertEquals($expected, $result);
  1893. $conditions = array('MysqlModel.id' => '');
  1894. $result = $this->Dbo->conditions($conditions, true, true, $this->model);
  1895. $expected = " WHERE `MysqlModel`.`id` IS NULL";
  1896. $this->assertEquals($expected, $result);
  1897. $result = $this->Dbo->conditions(array('Listing.beds >=' => 0));
  1898. $expected = " WHERE `Listing`.`beds` >= 0";
  1899. $this->assertEquals($expected, $result);
  1900. $result = $this->Dbo->conditions(array(
  1901. 'ASCII(SUBSTRING(keyword, 1, 1)) BETWEEN ? AND ?' => array(65, 90)
  1902. ));
  1903. $expected = ' WHERE ASCII(SUBSTRING(keyword, 1, 1)) BETWEEN 65 AND 90';
  1904. $this->assertEquals($expected, $result);
  1905. $result = $this->Dbo->conditions(array('or' => array(
  1906. '? BETWEEN Model.field1 AND Model.field2' => '2009-03-04'
  1907. )));
  1908. $expected = " WHERE '2009-03-04' BETWEEN Model.field1 AND Model.field2";
  1909. $this->assertEquals($expected, $result);
  1910. }
  1911. /**
  1912. * testArrayConditionsParsingComplexKeys method
  1913. *
  1914. * @return void
  1915. */
  1916. public function testArrayConditionsParsingComplexKeys() {
  1917. $result = $this->Dbo->conditions(array(
  1918. 'CAST(Book.created AS DATE)' => '2008-08-02'
  1919. ));
  1920. $expected = " WHERE CAST(`Book`.`created` AS DATE) = '2008-08-02'";
  1921. $this->assertEquals($expected, $result);
  1922. $result = $this->Dbo->conditions(array(
  1923. 'CAST(Book.created AS DATE) <=' => '2008-08-02'
  1924. ));
  1925. $expected = " WHERE CAST(`Book`.`created` AS DATE) <= '2008-08-02'";
  1926. $this->assertEquals($expected, $result);
  1927. $result = $this->Dbo->conditions(array(
  1928. '(Stats.clicks * 100) / Stats.views >' => 50
  1929. ));
  1930. $expected = " WHERE (`Stats`.`clicks` * 100) / `Stats`.`views` > 50";
  1931. $this->assertEquals($expected, $result);
  1932. }
  1933. /**
  1934. * testMixedConditionsParsing method
  1935. *
  1936. * @return void
  1937. */
  1938. public function testMixedConditionsParsing() {
  1939. $conditions[] = 'User.first_name = \'Firstname\'';
  1940. $conditions[] = array('User.last_name' => 'Lastname');
  1941. $result = $this->Dbo->conditions($conditions);
  1942. $expected = " WHERE `User`.`first_name` = 'Firstname' AND `User`.`last_name` = 'Lastname'";
  1943. $this->assertEquals($expected, $result);
  1944. $conditions = array(
  1945. 'Thread.project_id' => 5,
  1946. 'Thread.buyer_id' => 14,
  1947. '1=1 GROUP BY Thread.project_id'
  1948. );
  1949. $result = $this->Dbo->conditions($conditions);
  1950. $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);
  1951. }
  1952. /**
  1953. * testConditionsOptionalArguments method
  1954. *
  1955. * @return void
  1956. */
  1957. public function testConditionsOptionalArguments() {
  1958. $result = $this->Dbo->conditions( array('Member.name' => 'Mariano'), true, false);
  1959. $this->assertRegExp('/^\s*`Member`.`name`\s*=\s*\'Mariano\'\s*$/', $result);
  1960. $result = $this->Dbo->conditions( array(), true, false);
  1961. $this->assertRegExp('/^\s*1\s*=\s*1\s*$/', $result);
  1962. }
  1963. /**
  1964. * testConditionsWithModel
  1965. *
  1966. * @return void
  1967. */
  1968. public function testConditionsWithModel() {
  1969. $this->Model = new Article2();
  1970. $result = $this->Dbo->conditions(array('Article2.viewed >=' => 0), true, true, $this->Model);
  1971. $expected = " WHERE `Article2`.`viewed` >= 0";
  1972. $this->assertEquals($expected, $result);
  1973. $result = $this->Dbo->conditions(array('Article2.viewed >=' => '0'), true, true, $this->Model);
  1974. $expected = " WHERE `Article2`.`viewed` >= 0";
  1975. $this->assertEquals($expected, $result);
  1976. $result = $this->Dbo->conditions(array('Article2.viewed >=' => '1'), true, true, $this->Model);
  1977. $expected = " WHERE `Article2`.`viewed` >= 1";
  1978. $this->assertEquals($expected, $result);
  1979. $result = $this->Dbo->conditions(array('Article2.rate_sum BETWEEN ? AND ?' => array(0, 10)), true, true, $this->Model);
  1980. $expected = " WHERE `Article2`.`rate_sum` BETWEEN 0 AND 10";
  1981. $this->assertEquals($expected, $result);
  1982. $result = $this->Dbo->conditions(array('Article2.rate_sum BETWEEN ? AND ?' => array('0', '10')), true, true, $this->Model);
  1983. $expected = " WHERE `Article2`.`rate_sum` BETWEEN 0 AND 10";
  1984. $this->assertEquals($expected, $result);
  1985. $result = $this->Dbo->conditions(array('Article2.rate_sum BETWEEN ? AND ?' => array('1', '10')), true, true, $this->Model);
  1986. $expected = " WHERE `Article2`.`rate_sum` BETWEEN 1 AND 10";
  1987. $this->assertEquals($expected, $result);
  1988. }
  1989. /**
  1990. * testFieldParsing method
  1991. *
  1992. * @return void
  1993. */
  1994. public function testFieldParsing() {
  1995. $this->Model = new TestModel();
  1996. $result = $this->Dbo->fields($this->Model, 'Vendor', "Vendor.id, COUNT(Model.vendor_id) AS `Vendor`.`count`");
  1997. $expected = array('`Vendor`.`id`', 'COUNT(`Model`.`vendor_id`) AS `Vendor`.`count`');
  1998. $this->assertEquals($expected, $result);
  1999. $result = $this->Dbo->fields($this->Model, 'Vendor', "`Vendor`.`id`, COUNT(`Model`.`vendor_id`) AS `Vendor`.`count`");
  2000. $expected = array('`Vendor`.`id`', 'COUNT(`Model`.`vendor_id`) AS `Vendor`.`count`');
  2001. $this->assertEquals($expected, $result);
  2002. $result = $this->Dbo->fields($this->Model, 'Post', "CONCAT(REPEAT(' ', COUNT(Parent.name) - 1), Node.name) AS name, Node.created");
  2003. $expected = array("CONCAT(REPEAT(' ', COUNT(`Parent`.`name`) - 1), Node.name) AS name", "`Node`.`created`");
  2004. $this->assertEquals($expected, $result);
  2005. $result = $this->Dbo->fields($this->Model, null, 'round( (3.55441 * fooField), 3 ) AS test');
  2006. $this->assertEquals($result, array('round( (3.55441 * fooField), 3 ) AS test'));
  2007. $result = $this->Dbo->fields($this->Model, null, 'ROUND(`Rating`.`rate_total` / `Rating`.`rate_count`,2) AS rating');
  2008. $this->assertEquals($result, array('ROUND(`Rating`.`rate_total` / `Rating`.`rate_count`,2) AS rating'));
  2009. $result = $this->Dbo->fields($this->Model, null, 'ROUND(Rating.rate_total / Rating.rate_count,2) AS rating');
  2010. $this->assertEquals($result, array('ROUND(Rating.rate_total / Rating.rate_count,2) AS rating'));
  2011. $result = $this->Dbo->fields($this->Model, 'Post', "Node.created, CONCAT(REPEAT(' ', COUNT(Parent.name) - 1), Node.name) AS name");
  2012. $expected = array("`Node`.`created`", "CONCAT(REPEAT(' ', COUNT(`Parent`.`name`) - 1), Node.name) AS name");
  2013. $this->assertEquals($expected, $result);
  2014. $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");
  2015. $expected = array(
  2016. '2.2', 'COUNT(*)', 'SUM(`Something`.`else`) as sum', '`Node`.`created`',
  2017. "CONCAT(REPEAT(' ', COUNT(`Parent`.`name`) - 1), Node.name) AS name", '`Post`.`title`', '`Post`.`1`', '1.1'
  2018. );
  2019. $this->assertEquals($expected, $result);
  2020. $result = $this->Dbo->fields($this->Model, null, "(`Provider`.`star_total` / `Provider`.`total_ratings`) as `rating`");
  2021. $expected = array("(`Provider`.`star_total` / `Provider`.`total_ratings`) as `rating`");
  2022. $this->assertEquals($expected, $result);
  2023. $result = $this->Dbo->fields($this->Model, 'Post');
  2024. $expected = array(
  2025. '`Post`.`id`', '`Post`.`client_id`', '`Post`.`name`', '`Post`.`login`',
  2026. '`Post`.`passwd`', '`Post`.`addr_1`', '`Post`.`addr_2`', '`Post`.`zip_code`',
  2027. '`Post`.`city`', '`Post`.`country`', '`Post`.`phone`', '`Post`.`fax`',
  2028. '`Post`.`url`', '`Post`.`email`', '`Post`.`comments`', '`Post`.`last_login`',
  2029. '`Post`.`created`', '`Post`.`updated`'
  2030. );
  2031. $this->assertEquals($expected, $result);
  2032. $result = $this->Dbo->fields($this->Model, 'Other');
  2033. $expected = array(
  2034. '`Other`.`id`', '`Other`.`client_id`', '`Other`.`name`', '`Other`.`login`',
  2035. '`Other`.`passwd`', '`Other`.`addr_1`', '`Other`.`addr_2`', '`Other`.`zip_code`',
  2036. '`Other`.`city`', '`Other`.`country`', '`Other`.`phone`', '`Other`.`fax`',
  2037. '`Other`.`url`', '`Other`.`email`', '`Other`.`comments`', '`Other`.`last_login`',
  2038. '`Other`.`created`', '`Other`.`updated`'
  2039. );
  2040. $this->assertEquals($expected, $result);
  2041. $result = $this->Dbo->fields($this->Model, null, array(), false);
  2042. $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');
  2043. $this->assertEquals($expected, $result);
  2044. $result = $this->Dbo->fields($this->Model, null, 'COUNT(*)');
  2045. $expected = array('COUNT(*)');
  2046. $this->assertEquals($expected, $result);
  2047. $result = $this->Dbo->fields($this->Model, null, 'SUM(Thread.unread_buyer) AS ' . $this->Dbo->name('sum_unread_buyer'));
  2048. $expected = array('SUM(`Thread`.`unread_buyer`) AS `sum_unread_buyer`');
  2049. $this->assertEquals($expected, $result);
  2050. $result = $this->Dbo->fields($this->Model, null, 'name, count(*)');
  2051. $expected = array('`TestModel`.`name`', 'count(*)');
  2052. $this->assertEquals($expected, $result);
  2053. $result = $this->Dbo->fields($this->Model, null, 'count(*), name');
  2054. $expected = array('count(*)', '`TestModel`.`name`');
  2055. $this->assertEquals($expected, $result);
  2056. $result = $this->Dbo->fields(
  2057. $this->Model, null, 'field1, field2, field3, count(*), name'
  2058. );
  2059. $expected = array(
  2060. '`TestModel`.`field1`', '`TestModel`.`field2`',
  2061. '`TestModel`.`field3`', 'count(*)', '`TestModel`.`name`'
  2062. );
  2063. $this->assertEquals($expected, $result);
  2064. $result = $this->Dbo->fields($this->Model, null, array('dayofyear(now())'));
  2065. $expected = array('dayofyear(now())');
  2066. $this->assertEquals($expected, $result);
  2067. $result = $this->Dbo->fields($this->Model, null, array('MAX(Model.field) As Max'));
  2068. $expected = array('MAX(`Model`.`field`) As Max');
  2069. $this->assertEquals($expected, $result);
  2070. $result = $this->Dbo->fields($this->Model, null, array('Model.field AS AnotherName'));
  2071. $expected = array('`Model`.`field` AS `AnotherName`');
  2072. $this->assertEquals($expected, $result);
  2073. $result = $this->Dbo->fields($this->Model, null, array('field AS AnotherName'));
  2074. $expected = array('`field` AS `AnotherName`');
  2075. $this->assertEquals($expected, $result);
  2076. $result = $this->Dbo->fields($this->Model, null, array(
  2077. 'TestModel.field AS AnotherName'
  2078. ));
  2079. $expected = array('`TestModel`.`field` AS `AnotherName`');
  2080. $this->assertEquals($expected, $result);
  2081. $result = $this->Dbo->fields($this->Model, 'Foo', array(
  2082. 'id', 'title', '(user_count + discussion_count + post_count) AS score'
  2083. ));
  2084. $expected = array(
  2085. '`Foo`.`id`',
  2086. '`Foo`.`title`',
  2087. '(user_count + discussion_count + post_count) AS score'
  2088. );
  2089. $this->assertEquals($expected, $result);
  2090. }
  2091. /**
  2092. * test that fields() will accept objects made from DboSource::expression
  2093. *
  2094. * @return void
  2095. */
  2096. public function testFieldsWithExpression() {
  2097. $this->Model = new TestModel;
  2098. $expression = $this->Dbo->expression("CASE Sample.id WHEN 1 THEN 'Id One' ELSE 'Other Id' END AS case_col");
  2099. $result = $this->Dbo->fields($this->Model, null, array("id", $expression));
  2100. $expected = array(
  2101. '`TestModel`.`id`',
  2102. "CASE Sample.id WHEN 1 THEN 'Id One' ELSE 'Other Id' END AS case_col"
  2103. );
  2104. $this->assertEquals($expected, $result);
  2105. }
  2106. /**
  2107. * testRenderStatement method
  2108. *
  2109. * @return void
  2110. */
  2111. public function testRenderStatement() {
  2112. $result = $this->Dbo->renderStatement('select', array(
  2113. 'fields' => 'id', 'table' => 'table', 'conditions' => 'WHERE 1=1',
  2114. 'alias' => '', 'joins' => '', 'order' => '', 'limit' => '', 'group' => ''
  2115. ));
  2116. $this->assertRegExp('/^\s*SELECT\s+id\s+FROM\s+table\s+WHERE\s+1=1\s*$/', $result);
  2117. $result = $this->Dbo->renderStatement('update', array('fields' => 'value=2', 'table' => 'table', 'conditions' => 'WHERE 1=1', 'alias' => ''));
  2118. $this->assertRegExp('/^\s*UPDATE\s+table\s+SET\s+value=2\s+WHERE\s+1=1\s*$/', $result);
  2119. $result = $this->Dbo->renderStatement('update', array('fields' => 'value=2', 'table' => 'table', 'conditions' => 'WHERE 1=1', 'alias' => 'alias', 'joins' => ''));
  2120. $this->assertRegExp('/^\s*UPDATE\s+table\s+AS\s+alias\s+SET\s+value=2\s+WHERE\s+1=1\s*$/', $result);
  2121. $result = $this->Dbo->renderStatement('delete', array('fields' => 'value=2', 'table' => 'table', 'conditions' => 'WHERE 1=1', 'alias' => ''));
  2122. $this->assertRegExp('/^\s*DELETE\s+FROM\s+table\s+WHERE\s+1=1\s*$/', $result);
  2123. $result = $this->Dbo->renderStatement('delete', array('fields' => 'value=2', 'table' => 'table', 'conditions' => 'WHERE 1=1', 'alias' => 'alias', 'joins' => ''));
  2124. $this->assertRegExp('/^\s*DELETE\s+alias\s+FROM\s+table\s+AS\s+alias\s+WHERE\s+1=1\s*$/', $result);
  2125. }
  2126. /**
  2127. * testSchema method
  2128. *
  2129. * @return void
  2130. */
  2131. public function testSchema() {
  2132. $Schema = new CakeSchema();
  2133. $Schema->tables = array('table' => array(), 'anotherTable' => array());
  2134. $result = $this->Dbo->dropSchema($Schema, 'non_existing');
  2135. $this->assertTrue(empty($result));
  2136. $result = $this->Dbo->dropSchema($Schema, 'table');
  2137. $this->assertRegExp('/^\s*DROP TABLE IF EXISTS\s+' . $this->Dbo->fullTableName('table') . ';\s*$/s', $result);
  2138. }
  2139. /**
  2140. * testDropSchemaNoSchema method
  2141. *
  2142. * @expectedException PHPUnit_Framework_Error
  2143. * @return void
  2144. */
  2145. public function testDropSchemaNoSchema() {
  2146. $result = $this->Dbo->dropSchema(null);
  2147. }
  2148. /**
  2149. * testOrderParsing method
  2150. *
  2151. * @return void
  2152. */
  2153. public function testOrderParsing() {
  2154. $result = $this->Dbo->order("ADDTIME(Event.time_begin, '-06:00:00') ASC");
  2155. $expected = " ORDER BY ADDTIME(`Event`.`time_begin`, '-06:00:00') ASC";
  2156. $this->assertEquals($expected, $result);
  2157. $result = $this->Dbo->order("title, id");
  2158. $this->assertRegExp('/^\s*ORDER BY\s+`title`\s+ASC,\s+`id`\s+ASC\s*$/', $result);
  2159. $result = $this->Dbo->order("title desc, id desc");
  2160. $this->assertRegExp('/^\s*ORDER BY\s+`title`\s+desc,\s+`id`\s+desc\s*$/', $result);
  2161. $result = $this->Dbo->order(array("title desc, id desc"));
  2162. $this->assertRegExp('/^\s*ORDER BY\s+`title`\s+desc,\s+`id`\s+desc\s*$/', $result);
  2163. $result = $this->Dbo->order(array("title", "id"));
  2164. $this->assertRegExp('/^\s*ORDER BY\s+`title`\s+ASC,\s+`id`\s+ASC\s*$/', $result);
  2165. $result = $this->Dbo->order(array(array('title'), array('id')));
  2166. $this->assertRegExp('/^\s*ORDER BY\s+`title`\s+ASC,\s+`id`\s+ASC\s*$/', $result);
  2167. $result = $this->Dbo->order(array("Post.title" => 'asc', "Post.id" => 'desc'));
  2168. $this->assertRegExp('/^\s*ORDER BY\s+`Post`.`title`\s+asc,\s+`Post`.`id`\s+desc\s*$/', $result);
  2169. $result = $this->Dbo->order(array(array("Post.title" => 'asc', "Post.id" => 'desc')));
  2170. $this->assertRegExp('/^\s*ORDER BY\s+`Post`.`title`\s+asc,\s+`Post`.`id`\s+desc\s*$/', $result);
  2171. $result = $this->Dbo->order(array("title"));
  2172. $this->assertRegExp('/^\s*ORDER BY\s+`title`\s+ASC\s*$/', $result);
  2173. $result = $this->Dbo->order(array(array("title")));
  2174. $this->assertRegExp('/^\s*ORDER BY\s+`title`\s+ASC\s*$/', $result);
  2175. $result = $this->Dbo->order("Dealer.id = 7 desc, Dealer.id = 3 desc, Dealer.title asc");
  2176. $expected = " ORDER BY `Dealer`.`id` = 7 desc, `Dealer`.`id` = 3 desc, `Dealer`.`title` asc";
  2177. $this->assertEquals($expected, $result);
  2178. $result = $this->Dbo->order(array("Page.name" => "='test' DESC"));
  2179. $this->assertRegExp("/^\s*ORDER BY\s+`Page`\.`name`\s*='test'\s+DESC\s*$/", $result);
  2180. $result = $this->Dbo->order("Page.name = 'view' DESC");
  2181. $this->assertRegExp("/^\s*ORDER BY\s+`Page`\.`name`\s*=\s*'view'\s+DESC\s*$/", $result);
  2182. $result = $this->Dbo->order("(Post.views)");
  2183. $this->assertRegExp("/^\s*ORDER BY\s+\(`Post`\.`views`\)\s+ASC\s*$/", $result);
  2184. $result = $this->Dbo->order("(Post.views)*Post.views");
  2185. $this->assertRegExp("/^\s*ORDER BY\s+\(`Post`\.`views`\)\*`Post`\.`views`\s+ASC\s*$/", $result);
  2186. $result = $this->Dbo->order("(Post.views) * Post.views");
  2187. $this->assertRegExp("/^\s*ORDER BY\s+\(`Post`\.`views`\) \* `Post`\.`views`\s+ASC\s*$/", $result);
  2188. $result = $this->Dbo->order("(Model.field1 + Model.field2) * Model.field3");
  2189. $this->assertRegExp("/^\s*ORDER BY\s+\(`Model`\.`field1` \+ `Model`\.`field2`\) \* `Model`\.`field3`\s+ASC\s*$/", $result);
  2190. $result = $this->Dbo->order("Model.name+0 ASC");
  2191. $this->assertRegExp("/^\s*ORDER BY\s+`Model`\.`name`\+0\s+ASC\s*$/", $result);
  2192. $result = $this->Dbo->order("Anuncio.destaque & 2 DESC");
  2193. $expected = ' ORDER BY `Anuncio`.`destaque` & 2 DESC';
  2194. $this->assertEquals($expected, $result);
  2195. $result = $this->Dbo->order("3963.191 * id");
  2196. $expected = ' ORDER BY 3963.191 * id ASC';
  2197. $this->assertEquals($expected, $result);
  2198. $result = $this->Dbo->order(array('Property.sale_price IS NULL'));
  2199. $expected = ' ORDER BY `Property`.`sale_price` IS NULL ASC';
  2200. $this->assertEquals($expected, $result);
  2201. }
  2202. /**
  2203. * testComplexSortExpression method
  2204. *
  2205. * @return void
  2206. */
  2207. public function testComplexSortExpression() {
  2208. $result = $this->Dbo->order(array('(Model.field > 100) DESC', 'Model.field ASC'));
  2209. $this->assertRegExp("/^\s*ORDER BY\s+\(`Model`\.`field`\s+>\s+100\)\s+DESC,\s+`Model`\.`field`\s+ASC\s*$/", $result);
  2210. }
  2211. /**
  2212. * testCalculations method
  2213. *
  2214. * @return void
  2215. */
  2216. public function testCalculations() {
  2217. $this->Model = new TestModel();
  2218. $result = $this->Dbo->calculate($this->Model, 'count');
  2219. $this->assertEquals($result, 'COUNT(*) AS `count`');
  2220. $result = $this->Dbo->calculate($this->Model, 'count', array('id'));
  2221. $this->assertEquals($result, 'COUNT(`id`) AS `count`');
  2222. $result = $this->Dbo->calculate(
  2223. $this->Model,
  2224. 'count',
  2225. array($this->Dbo->expression('DISTINCT id'))
  2226. );
  2227. $this->assertEquals($result, 'COUNT(DISTINCT id) AS `count`');
  2228. $result = $this->Dbo->calculate($this->Model, 'count', array('id', 'id_count'));
  2229. $this->assertEquals($result, 'COUNT(`id`) AS `id_count`');
  2230. $result = $this->Dbo->calculate($this->Model, 'count', array('Model.id', 'id_count'));
  2231. $this->assertEquals($result, 'COUNT(`Model`.`id`) AS `id_count`');
  2232. $result = $this->Dbo->calculate($this->Model, 'max', array('id'));
  2233. $this->assertEquals($result, 'MAX(`id`) AS `id`');
  2234. $result = $this->Dbo->calculate($this->Model, 'max', array('Model.id', 'id'));
  2235. $this->assertEquals($result, 'MAX(`Model`.`id`) AS `id`');
  2236. $result = $this->Dbo->calculate($this->Model, 'max', array('`Model`.`id`', 'id'));
  2237. $this->assertEquals($result, 'MAX(`Model`.`id`) AS `id`');
  2238. $result = $this->Dbo->calculate($this->Model, 'min', array('`Model`.`id`', 'id'));
  2239. $this->assertEquals($result, 'MIN(`Model`.`id`) AS `id`');
  2240. $result = $this->Dbo->calculate($this->Model, 'min', 'left');
  2241. $this->assertEquals($result, 'MIN(`left`) AS `left`');
  2242. }
  2243. /**
  2244. * testLength method
  2245. *
  2246. * @return void
  2247. */
  2248. public function testLength() {
  2249. $result = $this->Dbo->length('varchar(255)');
  2250. $expected = 255;
  2251. $this->assertSame($expected, $result);
  2252. $result = $this->Dbo->length('int(11)');
  2253. $expected = 11;
  2254. $this->assertSame($expected, $result);
  2255. $result = $this->Dbo->length('float(5,3)');
  2256. $expected = '5,3';
  2257. $this->assertSame($expected, $result);
  2258. $result = $this->Dbo->length('decimal(5,2)');
  2259. $expected = '5,2';
  2260. $this->assertSame($expected, $result);
  2261. $result = $this->Dbo->length("enum('test','me','now')");
  2262. $expected = 4;
  2263. $this->assertSame($expected, $result);
  2264. $result = $this->Dbo->length("set('a','b','cd')");
  2265. $expected = 2;
  2266. $this->assertSame($expected, $result);
  2267. $result = $this->Dbo->length(false);
  2268. $this->assertTrue($result === null);
  2269. $result = $this->Dbo->length('datetime');
  2270. $expected = null;
  2271. $this->assertSame($expected, $result);
  2272. $result = $this->Dbo->length('text');
  2273. $expected = null;
  2274. $this->assertSame($expected, $result);
  2275. }
  2276. /**
  2277. * testBuildIndex method
  2278. *
  2279. * @return void
  2280. */
  2281. public function testBuildIndex() {
  2282. $data = array(
  2283. 'PRIMARY' => array('column' => 'id')
  2284. );
  2285. $result = $this->Dbo->buildIndex($data);
  2286. $expected = array('PRIMARY KEY (`id`)');
  2287. $this->assertSame($expected, $result);
  2288. $data = array(
  2289. 'MyIndex' => array('column' => 'id', 'unique' => true)
  2290. );
  2291. $result = $this->Dbo->buildIndex($data);
  2292. $expected = array('UNIQUE KEY `MyIndex` (`id`)');
  2293. $this->assertEquals($expected, $result);
  2294. $data = array(
  2295. 'MyIndex' => array('column' => array('id', 'name'), 'unique' => true)
  2296. );
  2297. $result = $this->Dbo->buildIndex($data);
  2298. $expected = array('UNIQUE KEY `MyIndex` (`id`, `name`)');
  2299. $this->assertEquals($expected, $result);
  2300. }
  2301. /**
  2302. * testBuildColumn method
  2303. *
  2304. * @return void
  2305. */
  2306. public function testBuildColumn2() {
  2307. $data = array(
  2308. 'name' => 'testName',
  2309. 'type' => 'string',
  2310. 'length' => 255,
  2311. 'default',
  2312. 'null' => true,
  2313. 'key'
  2314. );
  2315. $result = $this->Dbo->buildColumn($data);
  2316. $expected = '`testName` varchar(255) DEFAULT NULL';
  2317. $this->assertEquals($expected, $result);
  2318. $data = array(
  2319. 'name' => 'int_field',
  2320. 'type' => 'integer',
  2321. 'default' => '',
  2322. 'null' => false,
  2323. );
  2324. $restore = $this->Dbo->columns;
  2325. $this->Dbo->columns = array('integer' => array('name' => 'int', 'limit' => '11', 'formatter' => 'intval'), );
  2326. $result = $this->Dbo->buildColumn($data);
  2327. $expected = '`int_field` int(11) NOT NULL';
  2328. $this->assertEquals($expected, $result);
  2329. $this->Dbo->fieldParameters['param'] = array(
  2330. 'value' => 'COLLATE',
  2331. 'quote' => false,
  2332. 'join' => ' ',
  2333. 'column' => 'Collate',
  2334. 'position' => 'beforeDefault',
  2335. 'options' => array('GOOD', 'OK')
  2336. );
  2337. $data = array(
  2338. 'name' => 'int_field',
  2339. 'type' => 'integer',
  2340. 'default' => '',
  2341. 'null' => false,
  2342. 'param' => 'BAD'
  2343. );
  2344. $result = $this->Dbo->buildColumn($data);
  2345. $expected = '`int_field` int(11) NOT NULL';
  2346. $this->assertEquals($expected, $result);
  2347. $data = array(
  2348. 'name' => 'int_field',
  2349. 'type' => 'integer',
  2350. 'default' => '',
  2351. 'null' => false,
  2352. 'param' => 'GOOD'
  2353. );
  2354. $result = $this->Dbo->buildColumn($data);
  2355. $expected = '`int_field` int(11) COLLATE GOOD NOT NULL';
  2356. $this->assertEquals($expected, $result);
  2357. $this->Dbo->columns = $restore;
  2358. $data = array(
  2359. 'name' => 'created',
  2360. 'type' => 'timestamp',
  2361. 'default' => 'current_timestamp',
  2362. 'null' => false,
  2363. );
  2364. $result = $this->Dbo->buildColumn($data);
  2365. $expected = '`created` timestamp DEFAULT CURRENT_TIMESTAMP NOT NULL';
  2366. $this->assertEquals($expected, $result);
  2367. $data = array(
  2368. 'name' => 'created',
  2369. 'type' => 'timestamp',
  2370. 'default' => 'CURRENT_TIMESTAMP',
  2371. 'null' => true,
  2372. );
  2373. $result = $this->Dbo->buildColumn($data);
  2374. $expected = '`created` timestamp DEFAULT CURRENT_TIMESTAMP';
  2375. $this->assertEquals($expected, $result);
  2376. $data = array(
  2377. 'name' => 'modified',
  2378. 'type' => 'timestamp',
  2379. 'null' => true,
  2380. );
  2381. $result = $this->Dbo->buildColumn($data);
  2382. $expected = '`modified` timestamp NULL';
  2383. $this->assertEquals($expected, $result);
  2384. $data = array(
  2385. 'name' => 'modified',
  2386. 'type' => 'timestamp',
  2387. 'default' => null,
  2388. 'null' => true,
  2389. );
  2390. $result = $this->Dbo->buildColumn($data);
  2391. $expected = '`modified` timestamp NULL';
  2392. $this->assertEquals($expected, $result);
  2393. }
  2394. /**
  2395. * testBuildColumnBadType method
  2396. *
  2397. * @expectedException PHPUnit_Framework_Error
  2398. * @return void
  2399. */
  2400. public function testBuildColumnBadType() {
  2401. $data = array(
  2402. 'name' => 'testName',
  2403. 'type' => 'varchar(255)',
  2404. 'default',
  2405. 'null' => true,
  2406. 'key'
  2407. );
  2408. $this->Dbo->buildColumn($data);
  2409. }
  2410. /**
  2411. * test hasAny()
  2412. *
  2413. * @return void
  2414. */
  2415. public function testHasAny() {
  2416. $this->Dbo = $this->getMock('Mysql', array('connect', '_execute', 'execute', 'value'));
  2417. $this->Model = $this->getMock('TestModel', array('getDataSource'));
  2418. $this->Model->expects($this->any())
  2419. ->method('getDataSource')
  2420. ->will($this->returnValue($this->Dbo));
  2421. $this->Dbo->expects($this->at(0))->method('value')
  2422. ->with('harry')
  2423. ->will($this->returnValue("'harry'"));
  2424. $this->Dbo->expects($this->at(1))->method('execute')
  2425. ->with('SELECT COUNT(`TestModel`.`id`) AS count FROM `test_models` AS `TestModel` WHERE `TestModel`.`name` = \'harry\'');
  2426. $this->Dbo->expects($this->at(2))->method('execute')
  2427. ->with('SELECT COUNT(`TestModel`.`id`) AS count FROM `test_models` AS `TestModel` WHERE 1 = 1');
  2428. $this->Dbo->hasAny($this->Model, array('TestModel.name' => 'harry'));
  2429. $this->Dbo->hasAny($this->Model, array());
  2430. }
  2431. /**
  2432. * test fields generating usable virtual fields to use in query
  2433. *
  2434. * @return void
  2435. */
  2436. public function testVirtualFields() {
  2437. $this->loadFixtures('Article', 'Comment', 'Tag');
  2438. $this->Dbo->virtualFieldSeparator = '__';
  2439. $Article = ClassRegistry::init('Article');
  2440. $commentsTable = $this->Dbo->fullTableName('comments', false);
  2441. $Article->virtualFields = array(
  2442. 'this_moment' => 'NOW()',
  2443. 'two' => '1 + 1',
  2444. 'comment_count' => 'SELECT COUNT(*) FROM ' . $commentsTable .
  2445. ' WHERE Article.id = ' . $commentsTable . '.article_id'
  2446. );
  2447. $result = $this->Dbo->fields($Article);
  2448. $expected = array(
  2449. '`Article`.`id`',
  2450. '`Article`.`user_id`',
  2451. '`Article`.`title`',
  2452. '`Article`.`body`',
  2453. '`Article`.`published`',
  2454. '`Article`.`created`',
  2455. '`Article`.`updated`',
  2456. '(NOW()) AS `Article__this_moment`',
  2457. '(1 + 1) AS `Article__two`',
  2458. "(SELECT COUNT(*) FROM $commentsTable WHERE `Article`.`id` = `$commentsTable`.`article_id`) AS `Article__comment_count`"
  2459. );
  2460. $this->assertEquals($expected, $result);
  2461. $result = $this->Dbo->fields($Article, null, array('this_moment', 'title'));
  2462. $expected = array(
  2463. '`Article`.`title`',
  2464. '(NOW()) AS `Article__this_moment`',
  2465. );
  2466. $this->assertEquals($expected, $result);
  2467. $result = $this->Dbo->fields($Article, null, array('Article.title', 'Article.this_moment'));
  2468. $expected = array(
  2469. '`Article`.`title`',
  2470. '(NOW()) AS `Article__this_moment`',
  2471. );
  2472. $this->assertEquals($expected, $result);
  2473. $result = $this->Dbo->fields($Article, null, array('Article.this_moment', 'Article.title'));
  2474. $expected = array(
  2475. '`Article`.`title`',
  2476. '(NOW()) AS `Article__this_moment`',
  2477. );
  2478. $this->assertEquals($expected, $result);
  2479. $result = $this->Dbo->fields($Article, null, array('Article.*'));
  2480. $expected = array(
  2481. '`Article`.*',
  2482. '(NOW()) AS `Article__this_moment`',
  2483. '(1 + 1) AS `Article__two`',
  2484. "(SELECT COUNT(*) FROM $commentsTable WHERE `Article`.`id` = `$commentsTable`.`article_id`) AS `Article__comment_count`"
  2485. );
  2486. $this->assertEquals($expected, $result);
  2487. $result = $this->Dbo->fields($Article, null, array('*'));
  2488. $expected = array(
  2489. '*',
  2490. '(NOW()) AS `Article__this_moment`',
  2491. '(1 + 1) AS `Article__two`',
  2492. "(SELECT COUNT(*) FROM $commentsTable WHERE `Article`.`id` = `$commentsTable`.`article_id`) AS `Article__comment_count`"
  2493. );
  2494. $this->assertEquals($expected, $result);
  2495. }
  2496. /**
  2497. * test conditions to generate query conditions for virtual fields
  2498. *
  2499. * @return void
  2500. */
  2501. public function testVirtualFieldsInConditions() {
  2502. $Article = ClassRegistry::init('Article');
  2503. $commentsTable = $this->Dbo->fullTableName('comments', false);
  2504. $Article->virtualFields = array(
  2505. 'this_moment' => 'NOW()',
  2506. 'two' => '1 + 1',
  2507. 'comment_count' => 'SELECT COUNT(*) FROM ' . $commentsTable .
  2508. ' WHERE Article.id = ' . $commentsTable . '.article_id'
  2509. );
  2510. $conditions = array('two' => 2);
  2511. $result = $this->Dbo->conditions($conditions, true, false, $Article);
  2512. $expected = '(1 + 1) = 2';
  2513. $this->assertEquals($expected, $result);
  2514. $conditions = array('this_moment BETWEEN ? AND ?' => array(1,2));
  2515. $expected = 'NOW() BETWEEN 1 AND 2';
  2516. $result = $this->Dbo->conditions($conditions, true, false, $Article);
  2517. $this->assertEquals($expected, $result);
  2518. $conditions = array('comment_count >' => 5);
  2519. $expected = "(SELECT COUNT(*) FROM $commentsTable WHERE `Article`.`id` = `$commentsTable`.`article_id`) > 5";
  2520. $result = $this->Dbo->conditions($conditions, true, false, $Article);
  2521. $this->assertEquals($expected, $result);
  2522. $conditions = array('NOT' => array('two' => 2));
  2523. $result = $this->Dbo->conditions($conditions, true, false, $Article);
  2524. $expected = 'NOT ((1 + 1) = 2)';
  2525. $this->assertEquals($expected, $result);
  2526. }
  2527. /**
  2528. * test that virtualFields with complex functions and aliases work.
  2529. *
  2530. * @return void
  2531. */
  2532. public function testConditionsWithComplexVirtualFields() {
  2533. $Article = ClassRegistry::init('Article', 'Comment', 'Tag');
  2534. $Article->virtualFields = array(
  2535. 'distance' => 'ACOS(SIN(20 * PI() / 180)
  2536. * SIN(Article.latitude * PI() / 180)
  2537. + COS(20 * PI() / 180)
  2538. * COS(Article.latitude * PI() / 180)
  2539. * COS((50 - Article.longitude) * PI() / 180)
  2540. ) * 180 / PI() * 60 * 1.1515 * 1.609344'
  2541. );
  2542. $conditions = array('distance >=' => 20);
  2543. $result = $this->Dbo->conditions($conditions, true, true, $Article);
  2544. $this->assertRegExp('/\) >= 20/', $result);
  2545. $this->assertRegExp('/[`\'"]Article[`\'"].[`\'"]latitude[`\'"]/', $result);
  2546. $this->assertRegExp('/[`\'"]Article[`\'"].[`\'"]longitude[`\'"]/', $result);
  2547. }
  2548. /**
  2549. * test calculate to generate claculate statements on virtual fields
  2550. *
  2551. * @return void
  2552. */
  2553. public function testVirtualFieldsInCalculate() {
  2554. $Article = ClassRegistry::init('Article');
  2555. $commentsTable = $this->Dbo->fullTableName('comments', false);
  2556. $Article->virtualFields = array(
  2557. 'this_moment' => 'NOW()',
  2558. 'two' => '1 + 1',
  2559. 'comment_count' => 'SELECT COUNT(*) FROM ' . $commentsTable .
  2560. ' WHERE Article.id = ' . $commentsTable . '.article_id'
  2561. );
  2562. $result = $this->Dbo->calculate($Article, 'count', array('this_moment'));
  2563. $expected = 'COUNT(NOW()) AS `count`';
  2564. $this->assertEquals($expected, $result);
  2565. $result = $this->Dbo->calculate($Article, 'max', array('comment_count'));
  2566. $expected = "MAX(SELECT COUNT(*) FROM $commentsTable WHERE `Article`.`id` = `$commentsTable`.`article_id`) AS `comment_count`";
  2567. $this->assertEquals($expected, $result);
  2568. }
  2569. /**
  2570. * test reading virtual fields containing newlines when recursive > 0
  2571. *
  2572. * @return void
  2573. */
  2574. public function testReadVirtualFieldsWithNewLines() {
  2575. $Article = new Article();
  2576. $Article->recursive = 1;
  2577. $Article->virtualFields = array(
  2578. 'test' => '
  2579. User.id + User.id
  2580. '
  2581. );
  2582. $result = $this->Dbo->fields($Article, null, array());
  2583. $result = $this->Dbo->fields($Article, $Article->alias, $result);
  2584. $this->assertRegExp('/[`\"]User[`\"]\.[`\"]id[`\"] \+ [`\"]User[`\"]\.[`\"]id[`\"]/', $result[7]);
  2585. }
  2586. /**
  2587. * test group to generate GROUP BY statements on virtual fields
  2588. *
  2589. * @return void
  2590. */
  2591. public function testVirtualFieldsInGroup() {
  2592. $Article = ClassRegistry::init('Article');
  2593. $Article->virtualFields = array(
  2594. 'this_year' => 'YEAR(Article.created)'
  2595. );
  2596. $result = $this->Dbo->group('this_year', $Article);
  2597. $expected = " GROUP BY (YEAR(`Article`.`created`))";
  2598. $this->assertEquals($expected, $result);
  2599. }
  2600. /**
  2601. * test that virtualFields with complex functions and aliases work.
  2602. *
  2603. * @return void
  2604. */
  2605. public function testFieldsWithComplexVirtualFields() {
  2606. $Article = new Article();
  2607. $Article->virtualFields = array(
  2608. 'distance' => 'ACOS(SIN(20 * PI() / 180)
  2609. * SIN(Article.latitude * PI() / 180)
  2610. + COS(20 * PI() / 180)
  2611. * COS(Article.latitude * PI() / 180)
  2612. * COS((50 - Article.longitude) * PI() / 180)
  2613. ) * 180 / PI() * 60 * 1.1515 * 1.609344'
  2614. );
  2615. $fields = array('id', 'distance');
  2616. $result = $this->Dbo->fields($Article, null, $fields);
  2617. $qs = $this->Dbo->startQuote;
  2618. $qe = $this->Dbo->endQuote;
  2619. $this->assertEquals($result[0], "{$qs}Article{$qe}.{$qs}id{$qe}");
  2620. $this->assertRegExp('/Article__distance/', $result[1]);
  2621. $this->assertRegExp('/[`\'"]Article[`\'"].[`\'"]latitude[`\'"]/', $result[1]);
  2622. $this->assertRegExp('/[`\'"]Article[`\'"].[`\'"]longitude[`\'"]/', $result[1]);
  2623. }
  2624. /**
  2625. * test that execute runs queries.
  2626. *
  2627. * @return void
  2628. */
  2629. public function testExecute() {
  2630. $query = 'SELECT * FROM ' . $this->Dbo->fullTableName('articles') . ' WHERE 1 = 1';
  2631. $this->Dbo->took = null;
  2632. $this->Dbo->affected = null;
  2633. $result = $this->Dbo->execute($query, array('log' => false));
  2634. $this->assertNotNull($result, 'No query performed! %s');
  2635. $this->assertNull($this->Dbo->took, 'Stats were set %s');
  2636. $this->assertNull($this->Dbo->affected, 'Stats were set %s');
  2637. $result = $this->Dbo->execute($query);
  2638. $this->assertNotNull($result, 'No query performed! %s');
  2639. $this->assertNotNull($this->Dbo->took, 'Stats were not set %s');
  2640. $this->assertNotNull($this->Dbo->affected, 'Stats were not set %s');
  2641. }
  2642. /**
  2643. * test a full example of using virtual fields
  2644. *
  2645. * @return void
  2646. */
  2647. public function testVirtualFieldsFetch() {
  2648. $this->loadFixtures('Article', 'Comment');
  2649. $Article = ClassRegistry::init('Article');
  2650. $Article->virtualFields = array(
  2651. 'comment_count' => 'SELECT COUNT(*) FROM ' . $this->Dbo->fullTableName('comments') .
  2652. ' WHERE Article.id = ' . $this->Dbo->fullTableName('comments') . '.article_id'
  2653. );
  2654. $conditions = array('comment_count >' => 2);
  2655. $query = 'SELECT ' . join(',', $this->Dbo->fields($Article, null, array('id', 'comment_count'))) .
  2656. ' FROM ' . $this->Dbo->fullTableName($Article) . ' Article ' . $this->Dbo->conditions($conditions, true, true, $Article);
  2657. $result = $this->Dbo->fetchAll($query);
  2658. $expected = array(array(
  2659. 'Article' => array('id' => 1, 'comment_count' => 4)
  2660. ));
  2661. $this->assertEquals($expected, $result);
  2662. }
  2663. /**
  2664. * test reading complex virtualFields with subqueries.
  2665. *
  2666. * @return void
  2667. */
  2668. public function testVirtualFieldsComplexRead() {
  2669. $this->loadFixtures('DataTest', 'Article', 'Comment', 'User', 'Tag', 'ArticlesTag');
  2670. $Article = ClassRegistry::init('Article');
  2671. $commentTable = $this->Dbo->fullTableName('comments');
  2672. $Article = ClassRegistry::init('Article');
  2673. $Article->virtualFields = array(
  2674. 'comment_count' => 'SELECT COUNT(*) FROM ' . $commentTable .
  2675. ' AS Comment WHERE Article.id = Comment.article_id'
  2676. );
  2677. $result = $Article->find('all');
  2678. $this->assertTrue(count($result) > 0);
  2679. $this->assertTrue($result[0]['Article']['comment_count'] > 0);
  2680. $DataTest = ClassRegistry::init('DataTest');
  2681. $DataTest->virtualFields = array(
  2682. 'complicated' => 'ACOS(SIN(20 * PI() / 180)
  2683. * SIN(DataTest.float * PI() / 180)
  2684. + COS(20 * PI() / 180)
  2685. * COS(DataTest.count * PI() / 180)
  2686. * COS((50 - DataTest.float) * PI() / 180)
  2687. ) * 180 / PI() * 60 * 1.1515 * 1.609344'
  2688. );
  2689. $result = $DataTest->find('all');
  2690. $this->assertTrue(count($result) > 0);
  2691. $this->assertTrue($result[0]['DataTest']['complicated'] > 0);
  2692. }
  2693. /**
  2694. * testIntrospectType method
  2695. *
  2696. * @return void
  2697. */
  2698. public function testIntrospectType() {
  2699. $this->assertEquals($this->Dbo->introspectType(0), 'integer');
  2700. $this->assertEquals($this->Dbo->introspectType(2), 'integer');
  2701. $this->assertEquals($this->Dbo->introspectType('2'), 'string');
  2702. $this->assertEquals($this->Dbo->introspectType('2.2'), 'string');
  2703. $this->assertEquals($this->Dbo->introspectType(2.2), 'float');
  2704. $this->assertEquals($this->Dbo->introspectType('stringme'), 'string');
  2705. $this->assertEquals($this->Dbo->introspectType('0stringme'), 'string');
  2706. $data = array(2.2);
  2707. $this->assertEquals($this->Dbo->introspectType($data), 'float');
  2708. $data = array('2.2');
  2709. $this->assertEquals($this->Dbo->introspectType($data), 'float');
  2710. $data = array(2);
  2711. $this->assertEquals($this->Dbo->introspectType($data), 'integer');
  2712. $data = array('2');
  2713. $this->assertEquals($this->Dbo->introspectType($data), 'integer');
  2714. $data = array('string');
  2715. $this->assertEquals($this->Dbo->introspectType($data), 'string');
  2716. $data = array(2.2, '2.2');
  2717. $this->assertEquals($this->Dbo->introspectType($data), 'float');
  2718. $data = array(2, '2');
  2719. $this->assertEquals($this->Dbo->introspectType($data), 'integer');
  2720. $data = array('string one', 'string two');
  2721. $this->assertEquals($this->Dbo->introspectType($data), 'string');
  2722. $data = array('2.2', 3);
  2723. $this->assertEquals($this->Dbo->introspectType($data), 'integer');
  2724. $data = array('2.2', '0stringme');
  2725. $this->assertEquals($this->Dbo->introspectType($data), 'string');
  2726. $data = array(2.2, 3);
  2727. $this->assertEquals($this->Dbo->introspectType($data), 'integer');
  2728. $data = array(2.2, '0stringme');
  2729. $this->assertEquals($this->Dbo->introspectType($data), 'string');
  2730. $data = array(2, 'stringme');
  2731. $this->assertEquals($this->Dbo->introspectType($data), 'string');
  2732. $data = array(2, '2.2', 'stringgme');
  2733. $this->assertEquals($this->Dbo->introspectType($data), 'string');
  2734. $data = array(2, '2.2');
  2735. $this->assertEquals($this->Dbo->introspectType($data), 'integer');
  2736. $data = array(2, 2.2);
  2737. $this->assertEquals($this->Dbo->introspectType($data), 'integer');
  2738. // NULL
  2739. $result = $this->Dbo->value(null, 'boolean');
  2740. $this->assertEquals($result, 'NULL');
  2741. // EMPTY STRING
  2742. $result = $this->Dbo->value('', 'boolean');
  2743. $this->assertEquals($result, "'0'");
  2744. // BOOLEAN
  2745. $result = $this->Dbo->value('true', 'boolean');
  2746. $this->assertEquals($result, "'1'");
  2747. $result = $this->Dbo->value('false', 'boolean');
  2748. $this->assertEquals($result, "'1'");
  2749. $result = $this->Dbo->value(true, 'boolean');
  2750. $this->assertEquals($result, "'1'");
  2751. $result = $this->Dbo->value(false, 'boolean');
  2752. $this->assertEquals($result, "'0'");
  2753. $result = $this->Dbo->value(1, 'boolean');
  2754. $this->assertEquals($result, "'1'");
  2755. $result = $this->Dbo->value(0, 'boolean');
  2756. $this->assertEquals($result, "'0'");
  2757. $result = $this->Dbo->value('abc', 'boolean');
  2758. $this->assertEquals($result, "'1'");
  2759. $result = $this->Dbo->value(1.234, 'boolean');
  2760. $this->assertEquals($result, "'1'");
  2761. $result = $this->Dbo->value('1.234e05', 'boolean');
  2762. $this->assertEquals($result, "'1'");
  2763. // NUMBERS
  2764. $result = $this->Dbo->value(123, 'integer');
  2765. $this->assertEquals($result, 123);
  2766. $result = $this->Dbo->value('123', 'integer');
  2767. $this->assertEquals($result, '123');
  2768. $result = $this->Dbo->value('0123', 'integer');
  2769. $this->assertEquals($result, "'0123'");
  2770. $result = $this->Dbo->value('0x123ABC', 'integer');
  2771. $this->assertEquals($result, "'0x123ABC'");
  2772. $result = $this->Dbo->value('0x123', 'integer');
  2773. $this->assertEquals($result, "'0x123'");
  2774. $result = $this->Dbo->value(1.234, 'float');
  2775. $this->assertEquals($result, 1.234);
  2776. $result = $this->Dbo->value('1.234', 'float');
  2777. $this->assertEquals($result, '1.234');
  2778. $result = $this->Dbo->value(' 1.234 ', 'float');
  2779. $this->assertEquals($result, "' 1.234 '");
  2780. $result = $this->Dbo->value('1.234e05', 'float');
  2781. $this->assertEquals($result, "'1.234e05'");
  2782. $result = $this->Dbo->value('1.234e+5', 'float');
  2783. $this->assertEquals($result, "'1.234e+5'");
  2784. $result = $this->Dbo->value('1,234', 'float');
  2785. $this->assertEquals($result, "'1,234'");
  2786. $result = $this->Dbo->value('FFF', 'integer');
  2787. $this->assertEquals($result, "'FFF'");
  2788. $result = $this->Dbo->value('abc', 'integer');
  2789. $this->assertEquals($result, "'abc'");
  2790. // STRINGS
  2791. $result = $this->Dbo->value('123', 'string');
  2792. $this->assertEquals($result, "'123'");
  2793. $result = $this->Dbo->value(123, 'string');
  2794. $this->assertEquals($result, "'123'");
  2795. $result = $this->Dbo->value(1.234, 'string');
  2796. $this->assertEquals($result, "'1.234'");
  2797. $result = $this->Dbo->value('abc', 'string');
  2798. $this->assertEquals($result, "'abc'");
  2799. $result = $this->Dbo->value(' abc ', 'string');
  2800. $this->assertEquals($result, "' abc '");
  2801. $result = $this->Dbo->value('a bc', 'string');
  2802. $this->assertEquals($result, "'a bc'");
  2803. }
  2804. /**
  2805. * testRealQueries method
  2806. *
  2807. * @return void
  2808. */
  2809. public function testRealQueries() {
  2810. $this->loadFixtures('Apple', 'Article', 'User', 'Comment', 'Tag', 'Sample', 'ArticlesTag');
  2811. $Apple = ClassRegistry::init('Apple');
  2812. $Article = ClassRegistry::init('Article');
  2813. $result = $this->Dbo->rawQuery('SELECT color, name FROM ' . $this->Dbo->fullTableName('apples'));
  2814. $this->assertTrue(!empty($result));
  2815. $result = $this->Dbo->fetchRow($result);
  2816. $expected = array($this->Dbo->fullTableName('apples', false) => array(
  2817. 'color' => 'Red 1',
  2818. 'name' => 'Red Apple 1'
  2819. ));
  2820. $this->assertEquals($expected, $result);
  2821. $result = $this->Dbo->fetchAll('SELECT name FROM ' . $this->Dbo->fullTableName('apples') . ' ORDER BY id');
  2822. $expected = array(
  2823. array($this->Dbo->fullTableName('apples', false) => array('name' => 'Red Apple 1')),
  2824. array($this->Dbo->fullTableName('apples', false) => array('name' => 'Bright Red Apple')),
  2825. array($this->Dbo->fullTableName('apples', false) => array('name' => 'green blue')),
  2826. array($this->Dbo->fullTableName('apples', false) => array('name' => 'Test Name')),
  2827. array($this->Dbo->fullTableName('apples', false) => array('name' => 'Blue Green')),
  2828. array($this->Dbo->fullTableName('apples', false) => array('name' => 'My new apple')),
  2829. array($this->Dbo->fullTableName('apples', false) => array('name' => 'Some odd color'))
  2830. );
  2831. $this->assertEquals($expected, $result);
  2832. $result = $this->Dbo->field($this->Dbo->fullTableName('apples', false), 'SELECT color, name FROM ' . $this->Dbo->fullTableName('apples') . ' ORDER BY id');
  2833. $expected = array(
  2834. 'color' => 'Red 1',
  2835. 'name' => 'Red Apple 1'
  2836. );
  2837. $this->assertEquals($expected, $result);
  2838. $Apple->unbindModel(array(), false);
  2839. $result = $this->Dbo->read($Apple, array(
  2840. 'fields' => array($Apple->escapeField('name')),
  2841. 'conditions' => null,
  2842. 'recursive' => -1
  2843. ));
  2844. $expected = array(
  2845. array('Apple' => array('name' => 'Red Apple 1')),
  2846. array('Apple' => array('name' => 'Bright Red Apple')),
  2847. array('Apple' => array('name' => 'green blue')),
  2848. array('Apple' => array('name' => 'Test Name')),
  2849. array('Apple' => array('name' => 'Blue Green')),
  2850. array('Apple' => array('name' => 'My new apple')),
  2851. array('Apple' => array('name' => 'Some odd color'))
  2852. );
  2853. $this->assertEquals($expected, $result);
  2854. $result = $this->Dbo->read($Article, array(
  2855. 'fields' => array('id', 'user_id', 'title'),
  2856. 'conditions' => null,
  2857. 'recursive' => 1
  2858. ));
  2859. $this->assertTrue(Set::matches('/Article[id=1]', $result));
  2860. $this->assertTrue(Set::matches('/Comment[id=1]', $result));
  2861. $this->assertTrue(Set::matches('/Comment[id=2]', $result));
  2862. $this->assertFalse(Set::matches('/Comment[id=10]', $result));
  2863. }
  2864. /**
  2865. * @expectedException MissingConnectionException
  2866. * @return void
  2867. */
  2868. public function testExceptionOnBrokenConnection() {
  2869. $dbo = new Mysql(array(
  2870. 'driver' => 'mysql',
  2871. 'host' => 'imaginary_host',
  2872. 'login' => 'mark',
  2873. 'password' => 'inyurdatabase',
  2874. 'database' => 'imaginary'
  2875. ));
  2876. }
  2877. /**
  2878. * testStatements method
  2879. *
  2880. * @return void
  2881. */
  2882. public function testUpdateStatements() {
  2883. $this->loadFixtures('Article', 'User');
  2884. $test = ConnectionManager::getDatasource('test');
  2885. $this->Dbo = $this->getMock('Mysql', array('execute'), array($test->config));
  2886. $this->Dbo->expects($this->at(0))->method('execute')
  2887. ->with("UPDATE `articles` SET `field1` = 'value1' WHERE 1 = 1");
  2888. $this->Dbo->expects($this->at(1))->method('execute')
  2889. ->with("UPDATE `articles` AS `Article` LEFT JOIN `users` AS `User` ON (`Article`.`user_id` = `User`.`id`)" .
  2890. " SET `Article`.`field1` = 2 WHERE 2=2");
  2891. $this->Dbo->expects($this->at(2))->method('execute')
  2892. ->with("UPDATE `articles` AS `Article` LEFT JOIN `users` AS `User` ON (`Article`.`user_id` = `User`.`id`)" .
  2893. " SET `Article`.`field1` = 'value' WHERE `index` = 'val'");
  2894. $Article = new Article();
  2895. $this->Dbo->update($Article, array('field1'), array('value1'));
  2896. $this->Dbo->update($Article, array('field1'), array('2'), '2=2');
  2897. $this->Dbo->update($Article, array('field1'), array("'value'"), array('index' => 'val'));
  2898. }
  2899. /**
  2900. * Test deletes with a mock.
  2901. *
  2902. * @return void
  2903. */
  2904. public function testDeleteStatements() {
  2905. $this->loadFixtures('Article', 'User');
  2906. $test = ConnectionManager::getDatasource('test');
  2907. $this->Dbo = $this->getMock('Mysql', array('execute'), array($test->config));
  2908. $this->Dbo->expects($this->at(0))->method('execute')
  2909. ->with("DELETE FROM `articles` WHERE 1 = 1");
  2910. $this->Dbo->expects($this->at(1))->method('execute')
  2911. ->with("DELETE `Article` FROM `articles` AS `Article` LEFT JOIN `users` AS `User` ON (`Article`.`user_id` = `User`.`id`)" .
  2912. " WHERE 1 = 1");
  2913. $this->Dbo->expects($this->at(2))->method('execute')
  2914. ->with("DELETE `Article` FROM `articles` AS `Article` LEFT JOIN `users` AS `User` ON (`Article`.`user_id` = `User`.`id`)" .
  2915. " WHERE 2=2");
  2916. $Article = new Article();
  2917. $this->Dbo->delete($Article);
  2918. $this->Dbo->delete($Article, true);
  2919. $this->Dbo->delete($Article, '2=2');
  2920. }
  2921. }