PostgresTest.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974
  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. $schema = new CakeSchema(array('connection' => 'test'));
  481. $result = $schema->read(array(
  482. 'connection' => 'test',
  483. 'models' => array('DatatypeTest')
  484. ));
  485. $schema->tables = array(
  486. 'datatype_tests' => $result['tables']['missing']['datatype_tests']
  487. );
  488. $result = $db1->createSchema($schema, 'datatype_tests');
  489. $this->assertNotRegExp('/timestamp DEFAULT/', $result);
  490. $this->assertRegExp('/\"full_length\"\s*text\s.*,/', $result);
  491. $this->assertContains('timestamp ,', $result);
  492. $this->assertContains('"huge_int" bigint NOT NULL,', $result);
  493. $db1->query('DROP TABLE ' . $db1->fullTableName('datatype_tests'));
  494. $db1->query($result);
  495. $result2 = $schema->read(array(
  496. 'connection' => 'test',
  497. 'models' => array('DatatypeTest')
  498. ));
  499. $schema->tables = array('datatype_tests' => $result2['tables']['missing']['datatype_tests']);
  500. $result2 = $db1->createSchema($schema, 'datatype_tests');
  501. $this->assertEquals($result, $result2);
  502. $db1->query('DROP TABLE ' . $db1->fullTableName('datatype_tests'));
  503. }
  504. /**
  505. * Test index generation from table info.
  506. *
  507. * @return void
  508. */
  509. public function testIndexGeneration() {
  510. $name = $this->Dbo->fullTableName('index_test', false, false);
  511. $this->Dbo->query('CREATE TABLE ' . $name . ' ("id" serial NOT NULL PRIMARY KEY, "bool" integer, "small_char" varchar(50), "description" varchar(40) )');
  512. $this->Dbo->query('CREATE INDEX pointless_bool ON ' . $name . '("bool")');
  513. $this->Dbo->query('CREATE UNIQUE INDEX char_index ON ' . $name . '("small_char")');
  514. $expected = array(
  515. 'PRIMARY' => array('unique' => true, 'column' => 'id'),
  516. 'pointless_bool' => array('unique' => false, 'column' => 'bool'),
  517. 'char_index' => array('unique' => true, 'column' => 'small_char'),
  518. );
  519. $result = $this->Dbo->index($name);
  520. $this->Dbo->query('DROP TABLE ' . $name);
  521. $this->assertEquals($expected, $result);
  522. $name = $this->Dbo->fullTableName('index_test_2', false, false);
  523. $this->Dbo->query('CREATE TABLE ' . $name . ' ("id" serial NOT NULL PRIMARY KEY, "bool" integer, "small_char" varchar(50), "description" varchar(40) )');
  524. $this->Dbo->query('CREATE UNIQUE INDEX multi_col ON ' . $name . '("small_char", "bool")');
  525. $expected = array(
  526. 'PRIMARY' => array('unique' => true, 'column' => 'id'),
  527. 'multi_col' => array('unique' => true, 'column' => array('small_char', 'bool')),
  528. );
  529. $result = $this->Dbo->index($name);
  530. $this->Dbo->query('DROP TABLE ' . $name);
  531. $this->assertEquals($expected, $result);
  532. }
  533. /**
  534. * Test the alterSchema capabilities of postgres
  535. *
  536. * @return void
  537. */
  538. public function testAlterSchema() {
  539. $Old = new CakeSchema(array(
  540. 'connection' => 'test',
  541. 'name' => 'AlterPosts',
  542. 'alter_posts' => array(
  543. 'id' => array('type' => 'integer', 'key' => 'primary'),
  544. 'author_id' => array('type' => 'integer', 'null' => false),
  545. 'title' => array('type' => 'string', 'null' => true),
  546. 'body' => array('type' => 'text'),
  547. 'published' => array('type' => 'string', 'length' => 1, 'default' => 'N'),
  548. 'created' => array('type' => 'datetime'),
  549. 'updated' => array('type' => 'datetime'),
  550. )
  551. ));
  552. $this->Dbo->query($this->Dbo->createSchema($Old));
  553. $New = new CakeSchema(array(
  554. 'connection' => 'test',
  555. 'name' => 'AlterPosts',
  556. 'alter_posts' => array(
  557. 'id' => array('type' => 'integer', 'key' => 'primary'),
  558. 'author_id' => array('type' => 'integer', 'null' => true),
  559. 'title' => array('type' => 'string', 'null' => false, 'default' => 'my title'),
  560. 'body' => array('type' => 'string', 'length' => 500),
  561. 'status' => array('type' => 'integer', 'length' => 3, 'default' => 1),
  562. 'created' => array('type' => 'datetime'),
  563. 'updated' => array('type' => 'datetime'),
  564. )
  565. ));
  566. $this->Dbo->query($this->Dbo->alterSchema($New->compare($Old), 'alter_posts'));
  567. $model = new CakeTestModel(array('table' => 'alter_posts', 'ds' => 'test'));
  568. $result = $model->schema();
  569. $this->assertTrue(isset($result['status']));
  570. $this->assertFalse(isset($result['published']));
  571. $this->assertEquals('string', $result['body']['type']);
  572. $this->assertEquals(1, $result['status']['default']);
  573. $this->assertEquals(true, $result['author_id']['null']);
  574. $this->assertEquals(false, $result['title']['null']);
  575. $this->Dbo->query($this->Dbo->dropSchema($New));
  576. $New = new CakeSchema(array(
  577. 'connection' => 'test_suite',
  578. 'name' => 'AlterPosts',
  579. 'alter_posts' => array(
  580. 'id' => array('type' => 'string', 'length' => 36, 'key' => 'primary'),
  581. 'author_id' => array('type' => 'integer', 'null' => false),
  582. 'title' => array('type' => 'string', 'null' => true),
  583. 'body' => array('type' => 'text'),
  584. 'published' => array('type' => 'string', 'length' => 1, 'default' => 'N'),
  585. 'created' => array('type' => 'datetime'),
  586. 'updated' => array('type' => 'datetime'),
  587. )
  588. ));
  589. $result = $this->Dbo->alterSchema($New->compare($Old), 'alter_posts');
  590. $this->assertNotRegExp('/varchar\(36\) NOT NULL/i', $result);
  591. }
  592. /**
  593. * Test the alter index capabilities of postgres
  594. *
  595. * @return void
  596. */
  597. public function testAlterIndexes() {
  598. $this->Dbo->cacheSources = false;
  599. $schema1 = new CakeSchema(array(
  600. 'name' => 'AlterTest1',
  601. 'connection' => 'test',
  602. 'altertest' => array(
  603. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  604. 'name' => array('type' => 'string', 'null' => false, 'length' => 50),
  605. 'group1' => array('type' => 'integer', 'null' => true),
  606. 'group2' => array('type' => 'integer', 'null' => true)
  607. )
  608. ));
  609. $this->Dbo->rawQuery($this->Dbo->createSchema($schema1));
  610. $schema2 = new CakeSchema(array(
  611. 'name' => 'AlterTest2',
  612. 'connection' => 'test',
  613. 'altertest' => array(
  614. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  615. 'name' => array('type' => 'string', 'null' => false, 'length' => 50),
  616. 'group1' => array('type' => 'integer', 'null' => true),
  617. 'group2' => array('type' => 'integer', 'null' => true),
  618. 'indexes' => array(
  619. 'name_idx' => array('unique' => false, 'column' => 'name'),
  620. 'group_idx' => array('unique' => false, 'column' => 'group1'),
  621. 'compound_idx' => array('unique' => false, 'column' => array('group1', 'group2')),
  622. 'PRIMARY' => array('unique' => true, 'column' => 'id')
  623. )
  624. )
  625. ));
  626. $this->Dbo->query($this->Dbo->alterSchema($schema2->compare($schema1)));
  627. $indexes = $this->Dbo->index('altertest');
  628. $this->assertEquals($schema2->tables['altertest']['indexes'], $indexes);
  629. // Change three indexes, delete one and add another one
  630. $schema3 = new CakeSchema(array(
  631. 'name' => 'AlterTest3',
  632. 'connection' => 'test',
  633. 'altertest' => array(
  634. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  635. 'name' => array('type' => 'string', 'null' => false, 'length' => 50),
  636. 'group1' => array('type' => 'integer', 'null' => true),
  637. 'group2' => array('type' => 'integer', 'null' => true),
  638. 'indexes' => array(
  639. 'name_idx' => array('unique' => true, 'column' => 'name'),
  640. 'group_idx' => array('unique' => false, 'column' => 'group2'),
  641. 'compound_idx' => array('unique' => false, 'column' => array('group2', 'group1')),
  642. 'another_idx' => array('unique' => false, 'column' => array('group1', 'name')))
  643. )));
  644. $this->Dbo->query($this->Dbo->alterSchema($schema3->compare($schema2)));
  645. $indexes = $this->Dbo->index('altertest');
  646. $this->assertEquals($schema3->tables['altertest']['indexes'], $indexes);
  647. // Compare us to ourself.
  648. $this->assertEquals(array(), $schema3->compare($schema3));
  649. // Drop the indexes
  650. $this->Dbo->query($this->Dbo->alterSchema($schema1->compare($schema3)));
  651. $indexes = $this->Dbo->index('altertest');
  652. $this->assertEquals(array(), $indexes);
  653. $this->Dbo->query($this->Dbo->dropSchema($schema1));
  654. }
  655. /**
  656. * Test it is possible to use virtual field with postgresql
  657. *
  658. * @return void
  659. */
  660. public function testVirtualFields() {
  661. $this->loadFixtures('Article', 'Comment', 'User', 'Attachment', 'Tag', 'ArticlesTag');
  662. $Article = new Article;
  663. $Article->virtualFields = array(
  664. 'next_id' => 'Article.id + 1',
  665. 'complex' => 'Article.title || Article.body',
  666. 'functional' => 'COALESCE(User.user, Article.title)',
  667. 'subquery' => 'SELECT count(*) FROM ' . $Article->Comment->table
  668. );
  669. $result = $Article->find('first');
  670. $this->assertEquals(2, $result['Article']['next_id']);
  671. $this->assertEquals($result['Article']['complex'], $result['Article']['title'] . $result['Article']['body']);
  672. $this->assertEquals($result['Article']['functional'], $result['User']['user']);
  673. $this->assertEquals(6, $result['Article']['subquery']);
  674. }
  675. /**
  676. * Test that virtual fields work with SQL constants
  677. *
  678. * @return void
  679. */
  680. public function testVirtualFieldAsAConstant() {
  681. $this->loadFixtures('Article', 'Comment');
  682. $Article = ClassRegistry::init('Article');
  683. $Article->virtualFields = array(
  684. 'empty' => "NULL",
  685. 'number' => 43,
  686. 'truth' => 'TRUE'
  687. );
  688. $result = $Article->find('first');
  689. $this->assertNull($result['Article']['empty']);
  690. $this->assertTrue($result['Article']['truth']);
  691. $this->assertEquals(43, $result['Article']['number']);
  692. }
  693. /**
  694. * Tests additional order options for postgres
  695. *
  696. * @return void
  697. */
  698. public function testOrderAdditionalParams() {
  699. $result = $this->Dbo->order(array('title' => 'DESC NULLS FIRST', 'body' => 'DESC'));
  700. $expected = ' ORDER BY "title" DESC NULLS FIRST, "body" DESC';
  701. $this->assertEquals($expected, $result);
  702. }
  703. /**
  704. * Test it is possible to do a SELECT COUNT(DISTINCT Model.field)
  705. * query in postgres and it gets correctly quoted
  706. *
  707. * @return void
  708. */
  709. public function testQuoteDistinctInFunction() {
  710. $this->loadFixtures('Article');
  711. $Article = new Article;
  712. $result = $this->Dbo->fields($Article, null, array('COUNT(DISTINCT Article.id)'));
  713. $expected = array('COUNT(DISTINCT "Article"."id")');
  714. $this->assertEquals($expected, $result);
  715. $result = $this->Dbo->fields($Article, null, array('COUNT(DISTINCT id)'));
  716. $expected = array('COUNT(DISTINCT "id")');
  717. $this->assertEquals($expected, $result);
  718. $result = $this->Dbo->fields($Article, null, array('COUNT(DISTINCT FUNC(id))'));
  719. $expected = array('COUNT(DISTINCT FUNC("id"))');
  720. $this->assertEquals($expected, $result);
  721. }
  722. /**
  723. * test that saveAll works even with conditions that lack a model name.
  724. *
  725. * @return void
  726. */
  727. public function testUpdateAllWithNonQualifiedConditions() {
  728. $this->loadFixtures('Article');
  729. $Article = new Article();
  730. $result = $Article->updateAll(array('title' => "'Awesome'"), array('title' => 'Third Article'));
  731. $this->assertTrue($result);
  732. $result = $Article->find('count', array(
  733. 'conditions' => array('Article.title' => 'Awesome')
  734. ));
  735. $this->assertEquals(1, $result, 'Article count is wrong or fixture has changed.');
  736. }
  737. /**
  738. * test alterSchema on two tables.
  739. *
  740. * @return void
  741. */
  742. public function testAlteringTwoTables() {
  743. $schema1 = new CakeSchema(array(
  744. 'name' => 'AlterTest1',
  745. 'connection' => 'test',
  746. 'altertest' => array(
  747. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  748. 'name' => array('type' => 'string', 'null' => false, 'length' => 50),
  749. ),
  750. 'other_table' => array(
  751. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  752. 'name' => array('type' => 'string', 'null' => false, 'length' => 50),
  753. )
  754. ));
  755. $schema2 = new CakeSchema(array(
  756. 'name' => 'AlterTest1',
  757. 'connection' => 'test',
  758. 'altertest' => array(
  759. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  760. 'field_two' => array('type' => 'string', 'null' => false, 'length' => 50),
  761. ),
  762. 'other_table' => array(
  763. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  764. 'field_two' => array('type' => 'string', 'null' => false, 'length' => 50),
  765. )
  766. ));
  767. $result = $this->db->alterSchema($schema2->compare($schema1));
  768. $this->assertEquals(2, substr_count($result, 'field_two'), 'Too many fields');
  769. $this->assertFalse(strpos(';ALTER', $result), 'Too many semi colons');
  770. }
  771. /**
  772. * test encoding setting.
  773. *
  774. * @return void
  775. */
  776. public function testEncoding() {
  777. $result = $this->Dbo->setEncoding('UTF8');
  778. $this->assertTrue($result);
  779. $result = $this->Dbo->getEncoding();
  780. $this->assertEquals('UTF8', $result);
  781. $result = $this->Dbo->setEncoding('EUC_JP'); /* 'EUC_JP' is right character code name in PostgreSQL */
  782. $this->assertTrue($result);
  783. $result = $this->Dbo->getEncoding();
  784. $this->assertEquals('EUC_JP', $result);
  785. }
  786. /**
  787. * Test truncate with a mock.
  788. *
  789. * @return void
  790. */
  791. public function testTruncateStatements() {
  792. $this->loadFixtures('Article', 'User');
  793. $db = ConnectionManager::getDatasource('test');
  794. $schema = $db->config['schema'];
  795. $Article = new Article();
  796. $this->Dbo = $this->getMock('Postgres', array('execute'), array($db->config));
  797. $this->Dbo->expects($this->at(0))->method('execute')
  798. ->with("DELETE FROM \"$schema\".\"articles\"");
  799. $this->Dbo->truncate($Article);
  800. $this->Dbo->expects($this->at(0))->method('execute')
  801. ->with("DELETE FROM \"$schema\".\"articles\"");
  802. $this->Dbo->truncate('articles');
  803. // #2355: prevent duplicate prefix
  804. $this->Dbo->config['prefix'] = 'tbl_';
  805. $Article->tablePrefix = 'tbl_';
  806. $this->Dbo->expects($this->at(0))->method('execute')
  807. ->with("DELETE FROM \"$schema\".\"tbl_articles\"");
  808. $this->Dbo->truncate($Article);
  809. $this->Dbo->expects($this->at(0))->method('execute')
  810. ->with("DELETE FROM \"$schema\".\"tbl_articles\"");
  811. $this->Dbo->truncate('articles');
  812. }
  813. /**
  814. * Test nested transaction
  815. *
  816. * @return void
  817. */
  818. public function testNestedTransaction() {
  819. $this->skipIf($this->Dbo->nestedTransactionSupported() === false, 'The Postgres server do not support nested transaction');
  820. $this->loadFixtures('Article');
  821. $model = new Article();
  822. $model->hasOne = $model->hasMany = $model->belongsTo = $model->hasAndBelongsToMany = array();
  823. $model->cacheQueries = false;
  824. $this->Dbo->cacheMethods = false;
  825. $this->assertTrue($this->Dbo->begin());
  826. $this->assertNotEmpty($model->read(null, 1));
  827. $this->assertTrue($this->Dbo->begin());
  828. $this->assertTrue($model->delete(1));
  829. $this->assertEmpty($model->read(null, 1));
  830. $this->assertTrue($this->Dbo->rollback());
  831. $this->assertNotEmpty($model->read(null, 1));
  832. $this->assertTrue($this->Dbo->begin());
  833. $this->assertTrue($model->delete(1));
  834. $this->assertEmpty($model->read(null, 1));
  835. $this->assertTrue($this->Dbo->commit());
  836. $this->assertEmpty($model->read(null, 1));
  837. $this->assertTrue($this->Dbo->rollback());
  838. $this->assertNotEmpty($model->read(null, 1));
  839. }
  840. public function testResetSequence() {
  841. $model = new Article();
  842. $table = $this->Dbo->fullTableName($model, false);
  843. $fields = array(
  844. 'id', 'user_id', 'title', 'body', 'published',
  845. );
  846. $values = array(
  847. array(1, 1, 'test', 'first post', false),
  848. array(2, 1, 'test 2', 'second post post', false),
  849. );
  850. $this->Dbo->insertMulti($table, $fields, $values);
  851. $sequence = $this->Dbo->getSequence($table);
  852. $result = $this->Dbo->rawQuery("SELECT nextval('$sequence')");
  853. $original = $result->fetch(PDO::FETCH_ASSOC);
  854. $this->assertTrue($this->Dbo->resetSequence($table, 'id'));
  855. $result = $this->Dbo->rawQuery("SELECT currval('$sequence')");
  856. $new = $result->fetch(PDO::FETCH_ASSOC);
  857. $this->assertTrue($new['currval'] > $original['nextval'], 'Sequence did not update');
  858. }
  859. }