PostgresTest.php 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953
  1. <?php
  2. /**
  3. * DboPostgresTest file
  4. *
  5. * PHP 5
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright 2005-2012, 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-2012, 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('Postgres', 'Model/Datasource/Database');
  22. require_once dirname(dirname(dirname(__FILE__))) . DS . 'models.php';
  23. /**
  24. * DboPostgresTestDb class
  25. *
  26. * @package Cake.Test.Case.Model.Datasource.Database
  27. */
  28. class DboPostgresTestDb extends Postgres {
  29. /**
  30. * simulated property
  31. *
  32. * @var array
  33. */
  34. public $simulated = array();
  35. /**
  36. * execute method
  37. *
  38. * @param mixed $sql
  39. * @return void
  40. */
  41. protected function _execute($sql, $params = array(), $prepareOptions = array()) {
  42. $this->simulated[] = $sql;
  43. return null;
  44. }
  45. /**
  46. * getLastQuery method
  47. *
  48. * @return void
  49. */
  50. public function getLastQuery() {
  51. return $this->simulated[count($this->simulated) - 1];
  52. }
  53. }
  54. /**
  55. * PostgresTestModel class
  56. *
  57. * @package Cake.Test.Case.Model.Datasource.Database
  58. */
  59. class PostgresTestModel extends Model {
  60. /**
  61. * name property
  62. *
  63. * @var string 'PostgresTestModel'
  64. */
  65. public $name = 'PostgresTestModel';
  66. /**
  67. * useTable property
  68. *
  69. * @var bool false
  70. */
  71. public $useTable = false;
  72. /**
  73. * belongsTo property
  74. *
  75. * @var array
  76. */
  77. public $belongsTo = array(
  78. 'PostgresClientTestModel' => array(
  79. 'foreignKey' => 'client_id'
  80. )
  81. );
  82. /**
  83. * find method
  84. *
  85. * @param mixed $conditions
  86. * @param mixed $fields
  87. * @param mixed $order
  88. * @param mixed $recursive
  89. * @return void
  90. */
  91. public function find($conditions = null, $fields = null, $order = null, $recursive = null) {
  92. return $conditions;
  93. }
  94. /**
  95. * findAll method
  96. *
  97. * @param mixed $conditions
  98. * @param mixed $fields
  99. * @param mixed $order
  100. * @param mixed $recursive
  101. * @return void
  102. */
  103. public function findAll($conditions = null, $fields = null, $order = null, $recursive = null) {
  104. return $conditions;
  105. }
  106. /**
  107. * schema method
  108. *
  109. * @return void
  110. */
  111. public function schema($field = false) {
  112. return array(
  113. 'id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8'),
  114. 'client_id' => array('type' => 'integer', 'null' => '', 'default' => '0', 'length' => '11'),
  115. 'name' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'),
  116. 'login' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'),
  117. 'passwd' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '255'),
  118. 'addr_1' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '255'),
  119. 'addr_2' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '25'),
  120. 'zip_code' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
  121. 'city' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
  122. 'country' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
  123. 'phone' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
  124. 'fax' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
  125. 'url' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '255'),
  126. 'email' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
  127. 'comments' => array('type' => 'text', 'null' => '1', 'default' => '', 'length' => ''),
  128. 'last_login' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => ''),
  129. 'created' => array('type' => 'date', 'null' => '1', 'default' => '', 'length' => ''),
  130. 'updated' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => null)
  131. );
  132. }
  133. }
  134. /**
  135. * PostgresClientTestModel class
  136. *
  137. * @package Cake.Test.Case.Model.Datasource.Database
  138. */
  139. class PostgresClientTestModel extends Model {
  140. /**
  141. * name property
  142. *
  143. * @var string 'PostgresClientTestModel'
  144. */
  145. public $name = 'PostgresClientTestModel';
  146. /**
  147. * useTable property
  148. *
  149. * @var bool false
  150. */
  151. public $useTable = false;
  152. /**
  153. * schema method
  154. *
  155. * @return void
  156. */
  157. public function schema($field = false) {
  158. return array(
  159. 'id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8', 'key' => 'primary'),
  160. 'name' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'),
  161. 'email' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
  162. 'created' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => ''),
  163. 'updated' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => null)
  164. );
  165. }
  166. }
  167. /**
  168. * PostgresTest class
  169. *
  170. * @package Cake.Test.Case.Model.Datasource.Database
  171. */
  172. class PostgresTest extends CakeTestCase {
  173. /**
  174. * Do not automatically load fixtures for each test, they will be loaded manually
  175. * using CakeTestCase::loadFixtures
  176. *
  177. * @var boolean
  178. */
  179. public $autoFixtures = false;
  180. /**
  181. * Fixtures
  182. *
  183. * @var object
  184. */
  185. public $fixtures = array('core.user', 'core.binary_test', 'core.comment', 'core.article',
  186. 'core.tag', 'core.articles_tag', 'core.attachment', 'core.person', 'core.post', 'core.author',
  187. 'core.datatype',
  188. );
  189. /**
  190. * Actual DB connection used in testing
  191. *
  192. * @var DboSource
  193. */
  194. public $Dbo = null;
  195. /**
  196. * Simulated DB connection used in testing
  197. *
  198. * @var DboSource
  199. */
  200. public $Dbo2 = null;
  201. /**
  202. * Sets up a Dbo class instance for testing
  203. *
  204. */
  205. public function setUp() {
  206. Configure::write('Cache.disable', true);
  207. $this->Dbo = ConnectionManager::getDataSource('test');
  208. $this->skipIf(!($this->Dbo instanceof Postgres));
  209. $this->Dbo2 = new DboPostgresTestDb($this->Dbo->config, false);
  210. $this->model = new PostgresTestModel();
  211. }
  212. /**
  213. * Sets up a Dbo class instance for testing
  214. *
  215. */
  216. public function tearDown() {
  217. Configure::write('Cache.disable', false);
  218. unset($this->Dbo2);
  219. }
  220. /**
  221. * Test field quoting method
  222. *
  223. */
  224. public function testFieldQuoting() {
  225. $fields = array(
  226. '"PostgresTestModel"."id" AS "PostgresTestModel__id"',
  227. '"PostgresTestModel"."client_id" AS "PostgresTestModel__client_id"',
  228. '"PostgresTestModel"."name" AS "PostgresTestModel__name"',
  229. '"PostgresTestModel"."login" AS "PostgresTestModel__login"',
  230. '"PostgresTestModel"."passwd" AS "PostgresTestModel__passwd"',
  231. '"PostgresTestModel"."addr_1" AS "PostgresTestModel__addr_1"',
  232. '"PostgresTestModel"."addr_2" AS "PostgresTestModel__addr_2"',
  233. '"PostgresTestModel"."zip_code" AS "PostgresTestModel__zip_code"',
  234. '"PostgresTestModel"."city" AS "PostgresTestModel__city"',
  235. '"PostgresTestModel"."country" AS "PostgresTestModel__country"',
  236. '"PostgresTestModel"."phone" AS "PostgresTestModel__phone"',
  237. '"PostgresTestModel"."fax" AS "PostgresTestModel__fax"',
  238. '"PostgresTestModel"."url" AS "PostgresTestModel__url"',
  239. '"PostgresTestModel"."email" AS "PostgresTestModel__email"',
  240. '"PostgresTestModel"."comments" AS "PostgresTestModel__comments"',
  241. '"PostgresTestModel"."last_login" AS "PostgresTestModel__last_login"',
  242. '"PostgresTestModel"."created" AS "PostgresTestModel__created"',
  243. '"PostgresTestModel"."updated" AS "PostgresTestModel__updated"'
  244. );
  245. $result = $this->Dbo->fields($this->model);
  246. $expected = $fields;
  247. $this->assertEquals($expected, $result);
  248. $result = $this->Dbo->fields($this->model, null, 'PostgresTestModel.*');
  249. $expected = $fields;
  250. $this->assertEquals($expected, $result);
  251. $result = $this->Dbo->fields($this->model, null, array('*', 'AnotherModel.id', 'AnotherModel.name'));
  252. $expected = array_merge($fields, array(
  253. '"AnotherModel"."id" AS "AnotherModel__id"',
  254. '"AnotherModel"."name" AS "AnotherModel__name"'));
  255. $this->assertEquals($expected, $result);
  256. $result = $this->Dbo->fields($this->model, null, array('*', 'PostgresClientTestModel.*'));
  257. $expected = array_merge($fields, array(
  258. '"PostgresClientTestModel"."id" AS "PostgresClientTestModel__id"',
  259. '"PostgresClientTestModel"."name" AS "PostgresClientTestModel__name"',
  260. '"PostgresClientTestModel"."email" AS "PostgresClientTestModel__email"',
  261. '"PostgresClientTestModel"."created" AS "PostgresClientTestModel__created"',
  262. '"PostgresClientTestModel"."updated" AS "PostgresClientTestModel__updated"'));
  263. $this->assertEquals($expected, $result);
  264. }
  265. /**
  266. * testColumnParsing method
  267. *
  268. * @return void
  269. */
  270. public function testColumnParsing() {
  271. $this->assertEquals('text', $this->Dbo2->column('text'));
  272. $this->assertEquals('date', $this->Dbo2->column('date'));
  273. $this->assertEquals('boolean', $this->Dbo2->column('boolean'));
  274. $this->assertEquals('string', $this->Dbo2->column('character varying'));
  275. $this->assertEquals('time', $this->Dbo2->column('time without time zone'));
  276. $this->assertEquals('datetime', $this->Dbo2->column('timestamp without time zone'));
  277. $result = $this->Dbo2->column('bigint');
  278. $expected = 'biginteger';
  279. $this->assertEquals($expected, $result);
  280. }
  281. /**
  282. * testValueQuoting method
  283. *
  284. * @return void
  285. */
  286. public function testValueQuoting() {
  287. $this->assertEquals("1.200000", $this->Dbo->value(1.2, 'float'));
  288. $this->assertEquals("'1,2'", $this->Dbo->value('1,2', 'float'));
  289. $this->assertEquals("0", $this->Dbo->value('0', 'integer'));
  290. $this->assertEquals('NULL', $this->Dbo->value('', 'integer'));
  291. $this->assertEquals('NULL', $this->Dbo->value('', 'float'));
  292. $this->assertEquals("NULL", $this->Dbo->value('', 'integer', false));
  293. $this->assertEquals("NULL", $this->Dbo->value('', 'float', false));
  294. $this->assertEquals("'0.0'", $this->Dbo->value('0.0', 'float'));
  295. $this->assertEquals("'TRUE'", $this->Dbo->value('t', 'boolean'));
  296. $this->assertEquals("'FALSE'", $this->Dbo->value('f', 'boolean'));
  297. $this->assertEquals("'TRUE'", $this->Dbo->value(true));
  298. $this->assertEquals("'FALSE'", $this->Dbo->value(false));
  299. $this->assertEquals("'t'", $this->Dbo->value('t'));
  300. $this->assertEquals("'f'", $this->Dbo->value('f'));
  301. $this->assertEquals("'TRUE'", $this->Dbo->value('true', 'boolean'));
  302. $this->assertEquals("'FALSE'", $this->Dbo->value('false', 'boolean'));
  303. $this->assertEquals("'FALSE'", $this->Dbo->value('', 'boolean'));
  304. $this->assertEquals("'FALSE'", $this->Dbo->value(0, 'boolean'));
  305. $this->assertEquals("'TRUE'", $this->Dbo->value(1, 'boolean'));
  306. $this->assertEquals("'TRUE'", $this->Dbo->value('1', 'boolean'));
  307. $this->assertEquals("NULL", $this->Dbo->value(null, 'boolean'));
  308. $this->assertEquals("NULL", $this->Dbo->value(array()));
  309. }
  310. /**
  311. * test that localized floats don't cause trouble.
  312. *
  313. * @return void
  314. */
  315. public function testLocalizedFloats() {
  316. $restore = setlocale(LC_NUMERIC, 0);
  317. setlocale(LC_NUMERIC, 'de_DE');
  318. $result = $this->db->value(3.141593, 'float');
  319. $this->assertEquals("3.141593", $result);
  320. $result = $this->db->value(3.14);
  321. $this->assertEquals("3.140000", $result);
  322. setlocale(LC_NUMERIC, $restore);
  323. }
  324. /**
  325. * test that date and time columns do not generate errors with null and nullish values.
  326. *
  327. * @return void
  328. */
  329. public function testDateAndTimeAsNull() {
  330. $this->assertEquals('NULL', $this->Dbo->value(null, 'date'));
  331. $this->assertEquals('NULL', $this->Dbo->value('', 'date'));
  332. $this->assertEquals('NULL', $this->Dbo->value('', 'datetime'));
  333. $this->assertEquals('NULL', $this->Dbo->value(null, 'datetime'));
  334. $this->assertEquals('NULL', $this->Dbo->value('', 'timestamp'));
  335. $this->assertEquals('NULL', $this->Dbo->value(null, 'timestamp'));
  336. $this->assertEquals('NULL', $this->Dbo->value('', 'time'));
  337. $this->assertEquals('NULL', $this->Dbo->value(null, 'time'));
  338. }
  339. /**
  340. * Tests that different Postgres boolean 'flavors' are properly returned as native PHP booleans
  341. *
  342. * @return void
  343. */
  344. public function testBooleanNormalization() {
  345. $this->assertEquals(true, $this->Dbo2->boolean('t', false));
  346. $this->assertEquals(true, $this->Dbo2->boolean('true', false));
  347. $this->assertEquals(true, $this->Dbo2->boolean('TRUE', false));
  348. $this->assertEquals(true, $this->Dbo2->boolean(true, false));
  349. $this->assertEquals(true, $this->Dbo2->boolean(1, false));
  350. $this->assertEquals(true, $this->Dbo2->boolean(" ", false));
  351. $this->assertEquals(false, $this->Dbo2->boolean('f', false));
  352. $this->assertEquals(false, $this->Dbo2->boolean('false', false));
  353. $this->assertEquals(false, $this->Dbo2->boolean('FALSE', false));
  354. $this->assertEquals(false, $this->Dbo2->boolean(false, false));
  355. $this->assertEquals(false, $this->Dbo2->boolean(0, false));
  356. $this->assertEquals(false, $this->Dbo2->boolean('', false));
  357. }
  358. /**
  359. * test that default -> false in schemas works correctly.
  360. *
  361. * @return void
  362. */
  363. public function testBooleanDefaultFalseInSchema() {
  364. $this->loadFixtures('Datatype');
  365. $model = new Model(array('name' => 'Datatype', 'table' => 'datatypes', 'ds' => 'test'));
  366. $model->create();
  367. $this->assertSame(false, $model->data['Datatype']['bool']);
  368. }
  369. /**
  370. * testLastInsertIdMultipleInsert method
  371. *
  372. * @return void
  373. */
  374. public function testLastInsertIdMultipleInsert() {
  375. $this->loadFixtures('User');
  376. $db1 = ConnectionManager::getDataSource('test');
  377. $table = $db1->fullTableName('users', false);
  378. $password = '5f4dcc3b5aa765d61d8327deb882cf99';
  379. $db1->execute(
  380. "INSERT INTO {$table} (\"user\", password) VALUES ('mariano', '{$password}')"
  381. );
  382. $this->assertEquals(5, $db1->lastInsertId($table));
  383. $db1->execute("INSERT INTO {$table} (\"user\", password) VALUES ('hoge', '{$password}')");
  384. $this->assertEquals(6, $db1->lastInsertId($table));
  385. }
  386. /**
  387. * Tests that column types without default lengths in $columns do not have length values
  388. * applied when generating schemas.
  389. *
  390. * @return void
  391. */
  392. public function testColumnUseLength() {
  393. $result = array('name' => 'foo', 'type' => 'string', 'length' => 100, 'default' => 'FOO');
  394. $expected = '"foo" varchar(100) DEFAULT \'FOO\'';
  395. $this->assertEquals($expected, $this->Dbo->buildColumn($result));
  396. $result = array('name' => 'foo', 'type' => 'text', 'length' => 100, 'default' => 'FOO');
  397. $expected = '"foo" text DEFAULT \'FOO\'';
  398. $this->assertEquals($expected, $this->Dbo->buildColumn($result));
  399. }
  400. /**
  401. * Tests that binary data is escaped/unescaped properly on reads and writes
  402. *
  403. * @return void
  404. */
  405. public function testBinaryDataIntegrity() {
  406. $this->loadFixtures('BinaryTest');
  407. $data = '%PDF-1.3
  408. %ƒÂÚÂÎßÛ†–ƒ∆
  409. 4 0 obj
  410. << /Length 5 0 R /Filter /FlateDecode >>
  411. stream
  412. xµYMì€∆Ω„WÃ%)nï0¯îâ-«é]Q"πXµáÿ•Ip - P V,]Ú#c˚ˇ‰ut¥†∏Ti9 Ü=”›Ø_˜4>à∑‚Épcé¢Pxæ®2q\'
  413. 1UªbU ᡒ+ö«√[ıµ⁄ão"R∑"HiGæä€(å≠≈^Ãøsm?YlƒÃõªfi‹âEÚB&‚Î◊7bÒ^¸m°÷˛?2±Øs“fiu#®U√ˇú÷g¥C;ä")n})JºIÔ3ËSnÑÎ¥≤ıD∆¢∂Msx1üèG˚±Œ™⁄>¶ySïufØ ˝¸?UπÃã√6flÌÚC=øK?˝…s
  414. ˛§¯ˇ:-˜ò7€ÓFæ∂∑Õ˛∆“V’>ılflëÅd«ÜQdI ›ÎB%W¿ΩıÉn~h vêCS>«é˛(ØôK!€¡zB!√
  415. [œÜ"ûß ·iH¸[Àºæ∑¯¡L,ÀÚAlS∫ˆ=∫Œ≤cÄr&ˆÈ:√ÿ£˚È«4fl•À]vc›bÅôÿî=siXe4/¡p]ã]ôÆIœ™ Ωflà_ƒ‚G?«7 ùÿ ı¯K4ïIpV◊÷·\'éµóªÚæ>î
  416. ;›sú!2fl¬F•/f∑j£
  417. dw"IÊÜπ<ôÿˆ%IG1ytÛDflXg|Éòa§˜}C˛¿ÿe°G´Ú±jÍm~¿/∂hã<#-¥•ıùe87€t˜õ6w}´{æ
  418. m‹ê– ∆¡ 6⁄\
  419. rAÀBùZ3aË‚r$G·$ó0Ñ üâUY4È™¡%C∑Ÿ2rc<Iõ-cï.
  420. [ŒöâFA†É‡+QglMÉîÉÄúÌ|¸»#x7¥«MgVÎ-GGÚ• I?Á‘”Lzw∞pHů◊nefqCî.nÕeè∆ÿÛy¡˙fb≤üŒHÜAëÕNq=´@ ’cQdÖúAÉIqñŸ˘+2&∏ Àù.gÅ‚ƒœ3EPƒOi—‰:>ÍCäı
  421. =Õec=ëR˝”eñ=<V$ì˙+x+¢ïÒÕ<àeWå»–˚∫Õ d§&£àf ]fPA´âtënöå∏◊ó „Ë@∆≠K´÷˘}a_CI˚©yòHg,ôSSVìBƒl4 L.ÈY…á,2∂íäÙ.$ó¸CäŸ*€óy
  422. π?G,_√·ÆÎç=^Vkvo±ó{§ƒ2»±¨Ïüo»ëD-ãé fió¥cVÙ\'™G~\'p¢%* ã˚÷
  423. ªºnh˚ºO^∏…®[Ó“‚ÅfıÌ≥∫F!Eœ(π∑T6`¬tΩÆ0ì»rTÎ`»Ñ«
  424. ]≈åp˝)=¿Ô0∆öVÂmˇˆ„ø~¯ÁÔ∏b*fc»‡Îı„Ú}∆tœs∂Y∫ÜaÆ˙X∏~<ÿ·Ù vé1‹p¿TD∆ÔîÄ“úhˆ*Ú€îe)K –p¨ÚJ3Ÿ∞ã>ÊuNê°“√Ü ‹Ê9iÙ0˙AAEÍ ˙`∂£\'ûce•åƒX›ŸÁ´1SK{qdá"tÏ[wQ#SµBe∞∑µó…ÌV`B"Ñ≥„!è_Óφ-º*ºú¿Ë0ˆeê∂´ë+HFj…‡zvHÓN|ÔL÷ûñ3õÜ$z%sá…pÎóV38âs Çoµ•ß3†<9B·¨û~¢3)ÂxóÿÁCÕòÆ ∫Í=»ÿSπS;∆~±êÆTEp∑óÈ÷ÀuìDHÈ $ÉõæÜjû§"≤ÃONM®RËíRr{õS ∏Ê™op±W;ÂUÔ P∫kÔˇflTæ∑óflË” ÆC©Ô[≥◊HÁ˚¨hê"ÆbF?ú%h˙ˇ4xèÕ(ó2ÙáíM])Ñd|=fë-cI0ñL¢kÖêk‰Rƒ«ıÄWñ8mO3∏&√æËX¯Hó—ì]yF2»–˜ádàà‡‹Çο„≥7mªHAS∑¶.;Œx(1} _kd©.fidç48M\'àáªCp^Krí<ɉXÓıïl!Ì$N<ı∞B»G]…∂Ó¯>˛ÔbõÒπÀ•:ôO<j∂™œ%âÏ—>@È$pÖu‹Ê´-QqV ?V≥JÆÍqÛX8(lπï@zgÖ}Fe<ˇ‡Sñ“ÿ˜ê?6‡L∫Oß~µ –?ËeäÚ®YîÕ =Ü=¢DÁu*GvBk;)L¬N«î:flö∂≠ÇΩq„Ñm하Ë∂‚"û≥§:±≤i^ΩÑ!)Wıyŧô á„RÄ÷Òôc’≠—s™rı‚Pdêãh˘ßHVç5fifiÈF€çÌÛuçÖ/M=gëµ±ÿGû1coÔuñæ‘z®. õ∑7ÉÏÜÆ,°’H†ÍÉÌ∂7e º® íˆ⁄◊øNWK”ÂYµ‚ñé;µ¶gV-fl>µtË¥áßN2 ¯¶BaP-)eW.àôt^∏1›C∑Ö?L„&”5’4jvã–ªZ ÷+4% ´0l…»ú^°´© ûiπ∑é®óܱÒÿ‰ïˆÌ–dˆ◊Æ19rQ=Í|ı•rMæ¬;ò‰Y‰é9.” ‹˝V«ã¯∏,+ë®j*¡·/';
  425. $model = new AppModel(array('name' => 'BinaryTest', 'ds' => 'test'));
  426. $model->save(compact('data'));
  427. $result = $model->find('first');
  428. $this->assertEquals($data, $result['BinaryTest']['data']);
  429. }
  430. /**
  431. * Tests the syntax of generated schema indexes
  432. *
  433. * @return void
  434. */
  435. public function testSchemaIndexSyntax() {
  436. $schema = new CakeSchema();
  437. $schema->tables = array('i18n' => array(
  438. 'id' => array(
  439. 'type' => 'integer', 'null' => false, 'default' => null,
  440. 'length' => 10, 'key' => 'primary'
  441. ),
  442. 'locale' => array('type' => 'string', 'null' => false, 'length' => 6, 'key' => 'index'),
  443. 'model' => array('type' => 'string', 'null' => false, 'key' => 'index'),
  444. 'foreign_key' => array(
  445. 'type' => 'integer', 'null' => false, 'length' => 10, 'key' => 'index'
  446. ),
  447. 'field' => array('type' => 'string', 'null' => false, 'key' => 'index'),
  448. 'content' => array('type' => 'text', 'null' => true, 'default' => null),
  449. 'indexes' => array(
  450. 'PRIMARY' => array('column' => 'id', 'unique' => 1),
  451. 'locale' => array('column' => 'locale', 'unique' => 0),
  452. 'model' => array('column' => 'model', 'unique' => 0),
  453. 'row_id' => array('column' => 'foreign_key', 'unique' => 0),
  454. 'field' => array('column' => 'field', 'unique' => 0)
  455. )
  456. ));
  457. $result = $this->Dbo->createSchema($schema);
  458. $this->assertNotRegExp('/^CREATE INDEX(.+);,$/', $result);
  459. }
  460. /**
  461. * testCakeSchema method
  462. *
  463. * Test that schema generated postgresql queries are valid. ref #5696
  464. * Check that the create statement for a schema generated table is the same as the original sql
  465. *
  466. * @return void
  467. */
  468. public function testCakeSchema() {
  469. $db1 = ConnectionManager::getDataSource('test');
  470. $db1->cacheSources = false;
  471. $db1->rawQuery('CREATE TABLE ' . $db1->fullTableName('datatype_tests') . ' (
  472. id serial NOT NULL,
  473. "varchar" character varying(40) NOT NULL,
  474. "full_length" character varying NOT NULL,
  475. "huge_int" bigint NOT NULL,
  476. "timestamp" timestamp without time zone,
  477. "date" date,
  478. CONSTRAINT test_data_types_pkey PRIMARY KEY (id)
  479. )');
  480. $model = new Model(array('name' => 'DatatypeTest', 'ds' => 'test'));
  481. $schema = new CakeSchema(array('connection' => 'test'));
  482. $result = $schema->read(array(
  483. 'connection' => 'test',
  484. 'models' => array('DatatypeTest')
  485. ));
  486. $schema->tables = array(
  487. 'datatype_tests' => $result['tables']['missing']['datatype_tests']
  488. );
  489. $result = $db1->createSchema($schema, 'datatype_tests');
  490. $this->assertNotRegExp('/timestamp DEFAULT/', $result);
  491. $this->assertRegExp('/\"full_length\"\s*text\s.*,/', $result);
  492. $this->assertContains('timestamp ,', $result);
  493. $this->assertContains('"huge_int" bigint NOT NULL,', $result);
  494. $db1->query('DROP TABLE ' . $db1->fullTableName('datatype_tests'));
  495. $db1->query($result);
  496. $result2 = $schema->read(array(
  497. 'connection' => 'test',
  498. 'models' => array('DatatypeTest')
  499. ));
  500. $schema->tables = array('datatype_tests' => $result2['tables']['missing']['datatype_tests']);
  501. $result2 = $db1->createSchema($schema, 'datatype_tests');
  502. $this->assertEquals($result, $result2);
  503. $db1->query('DROP TABLE ' . $db1->fullTableName('datatype_tests'));
  504. }
  505. /**
  506. * Test index generation from table info.
  507. *
  508. * @return void
  509. */
  510. public function testIndexGeneration() {
  511. $name = $this->Dbo->fullTableName('index_test', false, false);
  512. $this->Dbo->query('CREATE TABLE ' . $name . ' ("id" serial NOT NULL PRIMARY KEY, "bool" integer, "small_char" varchar(50), "description" varchar(40) )');
  513. $this->Dbo->query('CREATE INDEX pointless_bool ON ' . $name . '("bool")');
  514. $this->Dbo->query('CREATE UNIQUE INDEX char_index ON ' . $name . '("small_char")');
  515. $expected = array(
  516. 'PRIMARY' => array('unique' => true, 'column' => 'id'),
  517. 'pointless_bool' => array('unique' => false, 'column' => 'bool'),
  518. 'char_index' => array('unique' => true, 'column' => 'small_char'),
  519. );
  520. $result = $this->Dbo->index($name);
  521. $this->Dbo->query('DROP TABLE ' . $name);
  522. $this->assertEquals($expected, $result);
  523. $name = $this->Dbo->fullTableName('index_test_2', false, false);
  524. $this->Dbo->query('CREATE TABLE ' . $name . ' ("id" serial NOT NULL PRIMARY KEY, "bool" integer, "small_char" varchar(50), "description" varchar(40) )');
  525. $this->Dbo->query('CREATE UNIQUE INDEX multi_col ON ' . $name . '("small_char", "bool")');
  526. $expected = array(
  527. 'PRIMARY' => array('unique' => true, 'column' => 'id'),
  528. 'multi_col' => array('unique' => true, 'column' => array('small_char', 'bool')),
  529. );
  530. $result = $this->Dbo->index($name);
  531. $this->Dbo->query('DROP TABLE ' . $name);
  532. $this->assertEquals($expected, $result);
  533. }
  534. /**
  535. * Test the alterSchema capabilities of postgres
  536. *
  537. * @return void
  538. */
  539. public function testAlterSchema() {
  540. $Old = new CakeSchema(array(
  541. 'connection' => 'test',
  542. 'name' => 'AlterPosts',
  543. 'alter_posts' => array(
  544. 'id' => array('type' => 'integer', 'key' => 'primary'),
  545. 'author_id' => array('type' => 'integer', 'null' => false),
  546. 'title' => array('type' => 'string', 'null' => true),
  547. 'body' => array('type' => 'text'),
  548. 'published' => array('type' => 'string', 'length' => 1, 'default' => 'N'),
  549. 'created' => array('type' => 'datetime'),
  550. 'updated' => array('type' => 'datetime'),
  551. )
  552. ));
  553. $this->Dbo->query($this->Dbo->createSchema($Old));
  554. $New = new CakeSchema(array(
  555. 'connection' => 'test',
  556. 'name' => 'AlterPosts',
  557. 'alter_posts' => array(
  558. 'id' => array('type' => 'integer', 'key' => 'primary'),
  559. 'author_id' => array('type' => 'integer', 'null' => true),
  560. 'title' => array('type' => 'string', 'null' => false, 'default' => 'my title'),
  561. 'body' => array('type' => 'string', 'length' => 500),
  562. 'status' => array('type' => 'integer', 'length' => 3, 'default' => 1),
  563. 'created' => array('type' => 'datetime'),
  564. 'updated' => array('type' => 'datetime'),
  565. )
  566. ));
  567. $this->Dbo->query($this->Dbo->alterSchema($New->compare($Old), 'alter_posts'));
  568. $model = new CakeTestModel(array('table' => 'alter_posts', 'ds' => 'test'));
  569. $result = $model->schema();
  570. $this->assertTrue(isset($result['status']));
  571. $this->assertFalse(isset($result['published']));
  572. $this->assertEquals('string', $result['body']['type']);
  573. $this->assertEquals(1, $result['status']['default']);
  574. $this->assertEquals(true, $result['author_id']['null']);
  575. $this->assertEquals(false, $result['title']['null']);
  576. $this->Dbo->query($this->Dbo->dropSchema($New));
  577. $New = new CakeSchema(array(
  578. 'connection' => 'test_suite',
  579. 'name' => 'AlterPosts',
  580. 'alter_posts' => array(
  581. 'id' => array('type' => 'string', 'length' => 36, 'key' => 'primary'),
  582. 'author_id' => array('type' => 'integer', 'null' => false),
  583. 'title' => array('type' => 'string', 'null' => true),
  584. 'body' => array('type' => 'text'),
  585. 'published' => array('type' => 'string', 'length' => 1, 'default' => 'N'),
  586. 'created' => array('type' => 'datetime'),
  587. 'updated' => array('type' => 'datetime'),
  588. )
  589. ));
  590. $result = $this->Dbo->alterSchema($New->compare($Old), 'alter_posts');
  591. $this->assertNotRegExp('/varchar\(36\) NOT NULL/i', $result);
  592. }
  593. /**
  594. * Test the alter index capabilities of postgres
  595. *
  596. * @return void
  597. */
  598. public function testAlterIndexes() {
  599. $this->Dbo->cacheSources = false;
  600. $schema1 = new CakeSchema(array(
  601. 'name' => 'AlterTest1',
  602. 'connection' => 'test',
  603. 'altertest' => array(
  604. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  605. 'name' => array('type' => 'string', 'null' => false, 'length' => 50),
  606. 'group1' => array('type' => 'integer', 'null' => true),
  607. 'group2' => array('type' => 'integer', 'null' => true)
  608. )
  609. ));
  610. $this->Dbo->rawQuery($this->Dbo->createSchema($schema1));
  611. $schema2 = new CakeSchema(array(
  612. 'name' => 'AlterTest2',
  613. 'connection' => 'test',
  614. 'altertest' => array(
  615. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  616. 'name' => array('type' => 'string', 'null' => false, 'length' => 50),
  617. 'group1' => array('type' => 'integer', 'null' => true),
  618. 'group2' => array('type' => 'integer', 'null' => true),
  619. 'indexes' => array(
  620. 'name_idx' => array('unique' => false, 'column' => 'name'),
  621. 'group_idx' => array('unique' => false, 'column' => 'group1'),
  622. 'compound_idx' => array('unique' => false, 'column' => array('group1', 'group2')),
  623. 'PRIMARY' => array('unique' => true, 'column' => 'id')
  624. )
  625. )
  626. ));
  627. $this->Dbo->query($this->Dbo->alterSchema($schema2->compare($schema1)));
  628. $indexes = $this->Dbo->index('altertest');
  629. $this->assertEquals($schema2->tables['altertest']['indexes'], $indexes);
  630. // Change three indexes, delete one and add another one
  631. $schema3 = new CakeSchema(array(
  632. 'name' => 'AlterTest3',
  633. 'connection' => 'test',
  634. 'altertest' => array(
  635. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  636. 'name' => array('type' => 'string', 'null' => false, 'length' => 50),
  637. 'group1' => array('type' => 'integer', 'null' => true),
  638. 'group2' => array('type' => 'integer', 'null' => true),
  639. 'indexes' => array(
  640. 'name_idx' => array('unique' => true, 'column' => 'name'),
  641. 'group_idx' => array('unique' => false, 'column' => 'group2'),
  642. 'compound_idx' => array('unique' => false, 'column' => array('group2', 'group1')),
  643. 'another_idx' => array('unique' => false, 'column' => array('group1', 'name')))
  644. )));
  645. $this->Dbo->query($this->Dbo->alterSchema($schema3->compare($schema2)));
  646. $indexes = $this->Dbo->index('altertest');
  647. $this->assertEquals($schema3->tables['altertest']['indexes'], $indexes);
  648. // Compare us to ourself.
  649. $this->assertEquals(array(), $schema3->compare($schema3));
  650. // Drop the indexes
  651. $this->Dbo->query($this->Dbo->alterSchema($schema1->compare($schema3)));
  652. $indexes = $this->Dbo->index('altertest');
  653. $this->assertEquals(array(), $indexes);
  654. $this->Dbo->query($this->Dbo->dropSchema($schema1));
  655. }
  656. /**
  657. * Test it is possible to use virtual field with postgresql
  658. *
  659. * @return void
  660. */
  661. public function testVirtualFields() {
  662. $this->loadFixtures('Article', 'Comment', 'User', 'Attachment', 'Tag', 'ArticlesTag');
  663. $Article = new Article;
  664. $Article->virtualFields = array(
  665. 'next_id' => 'Article.id + 1',
  666. 'complex' => 'Article.title || Article.body',
  667. 'functional' => 'COALESCE(User.user, Article.title)',
  668. 'subquery' => 'SELECT count(*) FROM ' . $Article->Comment->table
  669. );
  670. $result = $Article->find('first');
  671. $this->assertEquals(2, $result['Article']['next_id']);
  672. $this->assertEquals($result['Article']['complex'], $result['Article']['title'] . $result['Article']['body']);
  673. $this->assertEquals($result['Article']['functional'], $result['User']['user']);
  674. $this->assertEquals(6, $result['Article']['subquery']);
  675. }
  676. /**
  677. * Test that virtual fields work with SQL constants
  678. *
  679. * @return void
  680. */
  681. public function testVirtualFieldAsAConstant() {
  682. $this->loadFixtures('Article', 'Comment');
  683. $Article = ClassRegistry::init('Article');
  684. $Article->virtualFields = array(
  685. 'empty' => "NULL",
  686. 'number' => 43,
  687. 'truth' => 'TRUE'
  688. );
  689. $result = $Article->find('first');
  690. $this->assertNull($result['Article']['empty']);
  691. $this->assertTrue($result['Article']['truth']);
  692. $this->assertEquals(43, $result['Article']['number']);
  693. }
  694. /**
  695. * Tests additional order options for postgres
  696. *
  697. * @return void
  698. */
  699. public function testOrderAdditionalParams() {
  700. $result = $this->Dbo->order(array('title' => 'DESC NULLS FIRST', 'body' => 'DESC'));
  701. $expected = ' ORDER BY "title" DESC NULLS FIRST, "body" DESC';
  702. $this->assertEquals($expected, $result);
  703. }
  704. /**
  705. * Test it is possible to do a SELECT COUNT(DISTINCT Model.field)
  706. * query in postgres and it gets correctly quoted
  707. *
  708. * @return void
  709. */
  710. public function testQuoteDistinctInFunction() {
  711. $this->loadFixtures('Article');
  712. $Article = new Article;
  713. $result = $this->Dbo->fields($Article, null, array('COUNT(DISTINCT Article.id)'));
  714. $expected = array('COUNT(DISTINCT "Article"."id")');
  715. $this->assertEquals($expected, $result);
  716. $result = $this->Dbo->fields($Article, null, array('COUNT(DISTINCT id)'));
  717. $expected = array('COUNT(DISTINCT "id")');
  718. $this->assertEquals($expected, $result);
  719. $result = $this->Dbo->fields($Article, null, array('COUNT(DISTINCT FUNC(id))'));
  720. $expected = array('COUNT(DISTINCT FUNC("id"))');
  721. $this->assertEquals($expected, $result);
  722. }
  723. /**
  724. * test that saveAll works even with conditions that lack a model name.
  725. *
  726. * @return void
  727. */
  728. public function testUpdateAllWithNonQualifiedConditions() {
  729. $this->loadFixtures('Article');
  730. $Article = new Article();
  731. $result = $Article->updateAll(array('title' => "'Awesome'"), array('title' => 'Third Article'));
  732. $this->assertTrue($result);
  733. $result = $Article->find('count', array(
  734. 'conditions' => array('Article.title' => 'Awesome')
  735. ));
  736. $this->assertEquals(1, $result, 'Article count is wrong or fixture has changed.');
  737. }
  738. /**
  739. * test alterSchema on two tables.
  740. *
  741. * @return void
  742. */
  743. public function testAlteringTwoTables() {
  744. $schema1 = new CakeSchema(array(
  745. 'name' => 'AlterTest1',
  746. 'connection' => 'test',
  747. 'altertest' => array(
  748. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  749. 'name' => array('type' => 'string', 'null' => false, 'length' => 50),
  750. ),
  751. 'other_table' => array(
  752. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  753. 'name' => array('type' => 'string', 'null' => false, 'length' => 50),
  754. )
  755. ));
  756. $schema2 = new CakeSchema(array(
  757. 'name' => 'AlterTest1',
  758. 'connection' => 'test',
  759. 'altertest' => array(
  760. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  761. 'field_two' => array('type' => 'string', 'null' => false, 'length' => 50),
  762. ),
  763. 'other_table' => array(
  764. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  765. 'field_two' => array('type' => 'string', 'null' => false, 'length' => 50),
  766. )
  767. ));
  768. $result = $this->db->alterSchema($schema2->compare($schema1));
  769. $this->assertEquals(2, substr_count($result, 'field_two'), 'Too many fields');
  770. $this->assertFalse(strpos(';ALTER', $result), 'Too many semi colons');
  771. }
  772. /**
  773. * test encoding setting.
  774. *
  775. * @return void
  776. */
  777. public function testEncoding() {
  778. $result = $this->Dbo->setEncoding('UTF8');
  779. $this->assertTrue($result);
  780. $result = $this->Dbo->getEncoding();
  781. $this->assertEquals('UTF8', $result);
  782. $result = $this->Dbo->setEncoding('EUC_JP'); /* 'EUC_JP' is right character code name in PostgreSQL */
  783. $this->assertTrue($result);
  784. $result = $this->Dbo->getEncoding();
  785. $this->assertEquals('EUC_JP', $result);
  786. }
  787. /**
  788. * Test truncate with a mock.
  789. *
  790. * @return void
  791. */
  792. public function testTruncateStatements() {
  793. $this->loadFixtures('Article', 'User');
  794. $db = ConnectionManager::getDatasource('test');
  795. $schema = $db->config['schema'];
  796. $Article = new Article();
  797. $this->Dbo = $this->getMock('Postgres', array('execute'), array($db->config));
  798. $this->Dbo->expects($this->at(0))->method('execute')
  799. ->with("DELETE FROM \"$schema\".\"articles\"");
  800. $this->Dbo->truncate($Article);
  801. $this->Dbo->expects($this->at(0))->method('execute')
  802. ->with("DELETE FROM \"$schema\".\"articles\"");
  803. $this->Dbo->truncate('articles');
  804. // #2355: prevent duplicate prefix
  805. $this->Dbo->config['prefix'] = 'tbl_';
  806. $Article->tablePrefix = 'tbl_';
  807. $this->Dbo->expects($this->at(0))->method('execute')
  808. ->with("DELETE FROM \"$schema\".\"tbl_articles\"");
  809. $this->Dbo->truncate($Article);
  810. $this->Dbo->expects($this->at(0))->method('execute')
  811. ->with("DELETE FROM \"$schema\".\"tbl_articles\"");
  812. $this->Dbo->truncate('articles');
  813. }
  814. /**
  815. * Test nested transaction
  816. *
  817. * @return void
  818. */
  819. public function testNestedTransaction() {
  820. $this->skipIf($this->Dbo->nestedTransactionSupported() === false, 'The Postgres server do not support nested transaction');
  821. $this->loadFixtures('Article');
  822. $model = new Article();
  823. $model->hasOne = $model->hasMany = $model->belongsTo = $model->hasAndBelongsToMany = array();
  824. $model->cacheQueries = false;
  825. $this->Dbo->cacheMethods = false;
  826. $this->assertTrue($this->Dbo->begin());
  827. $this->assertNotEmpty($model->read(null, 1));
  828. $this->assertTrue($this->Dbo->begin());
  829. $this->assertTrue($model->delete(1));
  830. $this->assertEmpty($model->read(null, 1));
  831. $this->assertTrue($this->Dbo->rollback());
  832. $this->assertNotEmpty($model->read(null, 1));
  833. $this->assertTrue($this->Dbo->begin());
  834. $this->assertTrue($model->delete(1));
  835. $this->assertEmpty($model->read(null, 1));
  836. $this->assertTrue($this->Dbo->commit());
  837. $this->assertEmpty($model->read(null, 1));
  838. $this->assertTrue($this->Dbo->rollback());
  839. $this->assertNotEmpty($model->read(null, 1));
  840. }
  841. }