PageRenderTime 61ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

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

https://gitlab.com/fouzia23chowdhury/cakephpCRUD
PHP | 1203 lines | 816 code | 122 blank | 265 comment | 0 complexity | b60ac8635f1284fe25be3eb1331953ca MD5 | raw file
  1. <?php
  2. /**
  3. * DboPostgresTest file
  4. *
  5. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  6. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  7. *
  8. * Licensed under The MIT License
  9. * Redistributions of files must retain the above copyright notice.
  10. *
  11. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  12. * @link http://cakephp.org CakePHP(tm) Project
  13. * @package Cake.Test.Case.Model.Datasource.Database
  14. * @since CakePHP(tm) v 1.2.0
  15. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  16. */
  17. App::uses('Model', 'Model');
  18. App::uses('AppModel', 'Model');
  19. App::uses('Postgres', 'Model/Datasource/Database');
  20. require_once dirname(dirname(dirname(__FILE__))) . DS . 'models.php';
  21. /**
  22. * DboPostgresTestDb class
  23. *
  24. * @package Cake.Test.Case.Model.Datasource.Database
  25. */
  26. class DboPostgresTestDb extends Postgres {
  27. /**
  28. * simulated property
  29. *
  30. * @var array
  31. */
  32. public $simulated = array();
  33. /**
  34. * execute method
  35. *
  36. * @param mixed $sql
  37. * @return void
  38. */
  39. protected function _execute($sql, $params = array(), $prepareOptions = array()) {
  40. $this->simulated[] = $sql;
  41. return null;
  42. }
  43. /**
  44. * getLastQuery method
  45. *
  46. * @return void
  47. */
  48. public function getLastQuery() {
  49. return $this->simulated[count($this->simulated) - 1];
  50. }
  51. }
  52. /**
  53. * PostgresTestModel class
  54. *
  55. * @package Cake.Test.Case.Model.Datasource.Database
  56. */
  57. class PostgresTestModel extends Model {
  58. /**
  59. * useTable property
  60. *
  61. * @var bool
  62. */
  63. public $useTable = false;
  64. /**
  65. * belongsTo property
  66. *
  67. * @var array
  68. */
  69. public $belongsTo = array(
  70. 'PostgresClientTestModel' => array(
  71. 'foreignKey' => 'client_id'
  72. )
  73. );
  74. /**
  75. * find method
  76. *
  77. * @param mixed $conditions
  78. * @param mixed $fields
  79. * @param mixed $order
  80. * @param mixed $recursive
  81. * @return void
  82. */
  83. public function find($conditions = null, $fields = null, $order = null, $recursive = null) {
  84. return $conditions;
  85. }
  86. /**
  87. * findAll method
  88. *
  89. * @param mixed $conditions
  90. * @param mixed $fields
  91. * @param mixed $order
  92. * @param mixed $recursive
  93. * @return void
  94. */
  95. public function findAll($conditions = null, $fields = null, $order = null, $recursive = null) {
  96. return $conditions;
  97. }
  98. /**
  99. * schema method
  100. *
  101. * @return void
  102. */
  103. public function schema($field = false) {
  104. return array(
  105. 'id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8'),
  106. 'client_id' => array('type' => 'integer', 'null' => '', 'default' => '0', 'length' => '11'),
  107. 'name' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'),
  108. 'login' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'),
  109. 'passwd' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '255'),
  110. 'addr_1' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '255'),
  111. 'addr_2' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '25'),
  112. 'zip_code' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
  113. 'city' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
  114. 'country' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
  115. 'phone' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
  116. 'fax' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
  117. 'url' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '255'),
  118. 'email' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
  119. 'comments' => array('type' => 'text', 'null' => '1', 'default' => '', 'length' => ''),
  120. 'last_login' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => ''),
  121. 'created' => array('type' => 'date', 'null' => '1', 'default' => '', 'length' => ''),
  122. 'updated' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => null)
  123. );
  124. }
  125. }
  126. /**
  127. * PostgresClientTestModel class
  128. *
  129. * @package Cake.Test.Case.Model.Datasource.Database
  130. */
  131. class PostgresClientTestModel extends Model {
  132. /**
  133. * useTable property
  134. *
  135. * @var bool
  136. */
  137. public $useTable = false;
  138. /**
  139. * schema method
  140. *
  141. * @return void
  142. */
  143. public function schema($field = false) {
  144. return array(
  145. 'id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8', 'key' => 'primary'),
  146. 'name' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'),
  147. 'email' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
  148. 'created' => array('type' => 'datetime', 'null' => true, 'default' => null, 'length' => ''),
  149. 'updated' => array('type' => 'datetime', 'null' => true, 'default' => null, 'length' => null)
  150. );
  151. }
  152. }
  153. /**
  154. * PostgresTest class
  155. *
  156. * @package Cake.Test.Case.Model.Datasource.Database
  157. */
  158. class PostgresTest extends CakeTestCase {
  159. /**
  160. * Do not automatically load fixtures for each test, they will be loaded manually
  161. * using CakeTestCase::loadFixtures
  162. *
  163. * @var bool
  164. */
  165. public $autoFixtures = false;
  166. /**
  167. * Fixtures
  168. *
  169. * @var object
  170. */
  171. public $fixtures = array('core.user', 'core.binary_test', 'core.comment', 'core.article',
  172. 'core.tag', 'core.articles_tag', 'core.attachment', 'core.person', 'core.post', 'core.author',
  173. 'core.datatype',
  174. );
  175. /**
  176. * Actual DB connection used in testing
  177. *
  178. * @var DboSource
  179. */
  180. public $Dbo = null;
  181. /**
  182. * Simulated DB connection used in testing
  183. *
  184. * @var DboSource
  185. */
  186. public $Dbo2 = null;
  187. /**
  188. * Sets up a Dbo class instance for testing
  189. *
  190. * @return void
  191. */
  192. public function setUp() {
  193. parent::setUp();
  194. Configure::write('Cache.disable', true);
  195. $this->Dbo = ConnectionManager::getDataSource('test');
  196. $this->skipIf(!($this->Dbo instanceof Postgres));
  197. $this->Dbo2 = new DboPostgresTestDb($this->Dbo->config, false);
  198. $this->model = new PostgresTestModel();
  199. }
  200. /**
  201. * Sets up a Dbo class instance for testing
  202. *
  203. * @return void
  204. */
  205. public function tearDown() {
  206. parent::tearDown();
  207. Configure::write('Cache.disable', false);
  208. unset($this->Dbo2);
  209. }
  210. /**
  211. * Test field quoting method
  212. *
  213. * @return void
  214. */
  215. public function testFieldQuoting() {
  216. $fields = array(
  217. '"PostgresTestModel"."id" AS "PostgresTestModel__id"',
  218. '"PostgresTestModel"."client_id" AS "PostgresTestModel__client_id"',
  219. '"PostgresTestModel"."name" AS "PostgresTestModel__name"',
  220. '"PostgresTestModel"."login" AS "PostgresTestModel__login"',
  221. '"PostgresTestModel"."passwd" AS "PostgresTestModel__passwd"',
  222. '"PostgresTestModel"."addr_1" AS "PostgresTestModel__addr_1"',
  223. '"PostgresTestModel"."addr_2" AS "PostgresTestModel__addr_2"',
  224. '"PostgresTestModel"."zip_code" AS "PostgresTestModel__zip_code"',
  225. '"PostgresTestModel"."city" AS "PostgresTestModel__city"',
  226. '"PostgresTestModel"."country" AS "PostgresTestModel__country"',
  227. '"PostgresTestModel"."phone" AS "PostgresTestModel__phone"',
  228. '"PostgresTestModel"."fax" AS "PostgresTestModel__fax"',
  229. '"PostgresTestModel"."url" AS "PostgresTestModel__url"',
  230. '"PostgresTestModel"."email" AS "PostgresTestModel__email"',
  231. '"PostgresTestModel"."comments" AS "PostgresTestModel__comments"',
  232. '"PostgresTestModel"."last_login" AS "PostgresTestModel__last_login"',
  233. '"PostgresTestModel"."created" AS "PostgresTestModel__created"',
  234. '"PostgresTestModel"."updated" AS "PostgresTestModel__updated"'
  235. );
  236. $result = $this->Dbo->fields($this->model);
  237. $expected = $fields;
  238. $this->assertEquals($expected, $result);
  239. $result = $this->Dbo->fields($this->model, null, 'PostgresTestModel.*');
  240. $expected = $fields;
  241. $this->assertEquals($expected, $result);
  242. $result = $this->Dbo->fields($this->model, null, array('*', 'AnotherModel.id', 'AnotherModel.name'));
  243. $expected = array_merge($fields, array(
  244. '"AnotherModel"."id" AS "AnotherModel__id"',
  245. '"AnotherModel"."name" AS "AnotherModel__name"'));
  246. $this->assertEquals($expected, $result);
  247. $result = $this->Dbo->fields($this->model, null, array('*', 'PostgresClientTestModel.*'));
  248. $expected = array_merge($fields, array(
  249. '"PostgresClientTestModel"."id" AS "PostgresClientTestModel__id"',
  250. '"PostgresClientTestModel"."name" AS "PostgresClientTestModel__name"',
  251. '"PostgresClientTestModel"."email" AS "PostgresClientTestModel__email"',
  252. '"PostgresClientTestModel"."created" AS "PostgresClientTestModel__created"',
  253. '"PostgresClientTestModel"."updated" AS "PostgresClientTestModel__updated"'));
  254. $this->assertEquals($expected, $result);
  255. }
  256. /**
  257. * testColumnParsing method
  258. *
  259. * @return void
  260. */
  261. public function testColumnParsing() {
  262. $this->assertEquals('text', $this->Dbo2->column('text'));
  263. $this->assertEquals('date', $this->Dbo2->column('date'));
  264. $this->assertEquals('boolean', $this->Dbo2->column('boolean'));
  265. $this->assertEquals('string', $this->Dbo2->column('character varying'));
  266. $this->assertEquals('time', $this->Dbo2->column('time without time zone'));
  267. $this->assertEquals('datetime', $this->Dbo2->column('timestamp without time zone'));
  268. $this->assertEquals('decimal', $this->Dbo2->column('decimal'));
  269. $this->assertEquals('decimal', $this->Dbo2->column('numeric'));
  270. $this->assertEquals('float', $this->Dbo2->column('float'));
  271. $this->assertEquals('float', $this->Dbo2->column('double precision'));
  272. $result = $this->Dbo2->column('bigint');
  273. $expected = 'biginteger';
  274. $this->assertEquals($expected, $result);
  275. }
  276. /**
  277. * testValueQuoting method
  278. *
  279. * @return void
  280. */
  281. public function testValueQuoting() {
  282. $this->assertEquals("1.200000", $this->Dbo->value(1.2, 'float'));
  283. $this->assertEquals("'1,2'", $this->Dbo->value('1,2', 'float'));
  284. $this->assertEquals("0", $this->Dbo->value('0', 'integer'));
  285. $this->assertEquals('NULL', $this->Dbo->value('', 'integer'));
  286. $this->assertEquals('NULL', $this->Dbo->value('', 'float'));
  287. $this->assertEquals("NULL", $this->Dbo->value('', 'integer', false));
  288. $this->assertEquals("NULL", $this->Dbo->value('', 'float', false));
  289. $this->assertEquals("'0.0'", $this->Dbo->value('0.0', 'float'));
  290. $this->assertEquals("'TRUE'", $this->Dbo->value('t', 'boolean'));
  291. $this->assertEquals("'FALSE'", $this->Dbo->value('f', 'boolean'));
  292. $this->assertEquals("'TRUE'", $this->Dbo->value(true));
  293. $this->assertEquals("'FALSE'", $this->Dbo->value(false));
  294. $this->assertEquals("'t'", $this->Dbo->value('t'));
  295. $this->assertEquals("'f'", $this->Dbo->value('f'));
  296. $this->assertEquals("'TRUE'", $this->Dbo->value('true', 'boolean'));
  297. $this->assertEquals("'FALSE'", $this->Dbo->value('false', 'boolean'));
  298. $this->assertEquals("'FALSE'", $this->Dbo->value('', 'boolean'));
  299. $this->assertEquals("'FALSE'", $this->Dbo->value(0, 'boolean'));
  300. $this->assertEquals("'TRUE'", $this->Dbo->value(1, 'boolean'));
  301. $this->assertEquals("'TRUE'", $this->Dbo->value('1', 'boolean'));
  302. $this->assertEquals("NULL", $this->Dbo->value(null, 'boolean'));
  303. $this->assertEquals("NULL", $this->Dbo->value(array()));
  304. }
  305. /**
  306. * test that localized floats don't cause trouble.
  307. *
  308. * @return void
  309. */
  310. public function testLocalizedFloats() {
  311. $restore = setlocale(LC_NUMERIC, 0);
  312. $this->skipIf(setlocale(LC_NUMERIC, 'de_DE') === false, "The German locale isn't available.");
  313. $result = $this->db->value(3.141593, 'float');
  314. $this->assertEquals("3.141593", $result);
  315. $result = $this->db->value(3.14);
  316. $this->assertEquals("3.140000", $result);
  317. setlocale(LC_NUMERIC, $restore);
  318. }
  319. /**
  320. * test that date and time columns do not generate errors with null and nullish values.
  321. *
  322. * @return void
  323. */
  324. public function testDateAndTimeAsNull() {
  325. $this->assertEquals('NULL', $this->Dbo->value(null, 'date'));
  326. $this->assertEquals('NULL', $this->Dbo->value('', 'date'));
  327. $this->assertEquals('NULL', $this->Dbo->value('', 'datetime'));
  328. $this->assertEquals('NULL', $this->Dbo->value(null, 'datetime'));
  329. $this->assertEquals('NULL', $this->Dbo->value('', 'timestamp'));
  330. $this->assertEquals('NULL', $this->Dbo->value(null, 'timestamp'));
  331. $this->assertEquals('NULL', $this->Dbo->value('', 'time'));
  332. $this->assertEquals('NULL', $this->Dbo->value(null, 'time'));
  333. }
  334. /**
  335. * Tests that different Postgres boolean 'flavors' are properly returned as native PHP booleans
  336. *
  337. * @return void
  338. */
  339. public function testBooleanNormalization() {
  340. $this->assertEquals(true, $this->Dbo2->boolean('t', false));
  341. $this->assertEquals(true, $this->Dbo2->boolean('true', false));
  342. $this->assertEquals(true, $this->Dbo2->boolean('TRUE', false));
  343. $this->assertEquals(true, $this->Dbo2->boolean(true, false));
  344. $this->assertEquals(true, $this->Dbo2->boolean(1, false));
  345. $this->assertEquals(true, $this->Dbo2->boolean(" ", false));
  346. $this->assertEquals(false, $this->Dbo2->boolean('f', false));
  347. $this->assertEquals(false, $this->Dbo2->boolean('false', false));
  348. $this->assertEquals(false, $this->Dbo2->boolean('FALSE', false));
  349. $this->assertEquals(false, $this->Dbo2->boolean(false, false));
  350. $this->assertEquals(false, $this->Dbo2->boolean(0, false));
  351. $this->assertEquals(false, $this->Dbo2->boolean('', false));
  352. }
  353. /**
  354. * test that default -> false in schemas works correctly.
  355. *
  356. * @return void
  357. */
  358. public function testBooleanDefaultFalseInSchema() {
  359. $this->loadFixtures('Datatype');
  360. $model = new Model(array('name' => 'Datatype', 'table' => 'datatypes', 'ds' => 'test'));
  361. $model->create();
  362. $this->assertSame(false, $model->data['Datatype']['bool']);
  363. }
  364. /**
  365. * testLastInsertIdMultipleInsert method
  366. *
  367. * @return void
  368. */
  369. public function testLastInsertIdMultipleInsert() {
  370. $this->loadFixtures('User');
  371. $db1 = ConnectionManager::getDataSource('test');
  372. $table = $db1->fullTableName('users', false);
  373. $password = '5f4dcc3b5aa765d61d8327deb882cf99';
  374. $db1->execute(
  375. "INSERT INTO {$table} (\"user\", password) VALUES ('mariano', '{$password}')"
  376. );
  377. $this->assertEquals(5, $db1->lastInsertId($table));
  378. $db1->execute("INSERT INTO {$table} (\"user\", password) VALUES ('hoge', '{$password}')");
  379. $this->assertEquals(6, $db1->lastInsertId($table));
  380. }
  381. /**
  382. * Tests that column types without default lengths in $columns do not have length values
  383. * applied when generating schemas.
  384. *
  385. * @return void
  386. */
  387. public function testColumnUseLength() {
  388. $result = array('name' => 'foo', 'type' => 'string', 'length' => 100, 'default' => 'FOO');
  389. $expected = '"foo" varchar(100) DEFAULT \'FOO\'';
  390. $this->assertEquals($expected, $this->Dbo->buildColumn($result));
  391. $result = array('name' => 'foo', 'type' => 'text', 'length' => 100, 'default' => 'FOO');
  392. $expected = '"foo" text DEFAULT \'FOO\'';
  393. $this->assertEquals($expected, $this->Dbo->buildColumn($result));
  394. }
  395. /**
  396. * Tests that binary data is escaped/unescaped properly on reads and writes
  397. *
  398. * @return void
  399. */
  400. public function testBinaryDataIntegrity() {
  401. $this->loadFixtures('BinaryTest');
  402. $data = '%PDF-1.3
  403. %ƒÂÚÂÎßÛ†–ƒ∆
  404. 4 0 obj
  405. << /Length 5 0 R /Filter /FlateDecode >>
  406. stream
  407. xÂľYMì€∆Ω„ƒ%)nĂŻ0ÂŻĂŽâ-ÂŤĂŠ]Q"πXµáÿ•Ip - P V,]Ú#c˚ˇ‰ut¥†∏Ti9 Ü=”›Ø_˜4>à∑‚ÉpcĂŠ¢PxĂŚÂŽ2q\'
  408. 1UÂŞbU ᡒ+ö«√[ıµ⁄ão"R∑"HiGĂŚä€(å≠≈^Ãøsm?YlƒÃõªfi‹âšB&‚Î◊7’^¸°ĂˇË›?2¹Ø€œďŹu#ÂŽU√ˇúág¼C;ä")n})JÂşIÔ3ËSnÑÎ¥≤ıD∆¢∂Msx1ĂźèG˚±Œ™⁄>ÂśySĂŻufØ ˝¸?UπÃã√6flÌÚC=øK?˝…s
  409. ˛§¯ˇ:-˜ò7€ÓFæ∂∑Õ˛∆“€™>ÄąlflëÅd«ÜQdI ›ÎB%W¿ΊıÉn~h vĂŞCS>ÂŤĂŠ˛(ØôK!€¡zB!√
  410. [œÜ"ûß ·iH¸[Àºæ∑¯¡L,ÀÚAlS∫ˆ=∫Œ≤cÄr&ˆÈ:√ÿ£˚È«4fl•À]vc›bÅôÿî=siXe4/¡p]ã]ôÆIœ™ Ωflà_ƒ‚G?«7 ùÿ ı¯K4ïIpV◊÷·\'éµóªÚæ>î
  411. ;›sĂş!2flÂŹF•/ˆ‘jÂŁ
  412. dw"IÊÜπ<ôÿˆ%IG1ytÛDflXg|Éòa§˜}C˛¿ÿe°G´Ú±jÍm~¿/∂hã<#-¥•ıùe87€t˜õ6w}´{æ
  413. €šĂŞâ€“ ∆¡ 6⁄\
  414. rAÀBĂšZ3aË‚r$G¡$Ăł0Ñ ßâUY4È™¡%ˆ‘Ÿ2rc<IĂľ-cĂŻ.
  415. [ŒöâF€ Ă‰â€Ą+QglMÉîÉÄúÌ|¸#x7ÂĽÂŤMgVÎ-Gšâ€˘Â I?Á‘”Lzw∞pHů◊nefqCĂŽ.•¨∆ÿÛyÂĄ˙fb≤üŒœAëÕNq=´@ ’cQdÖúAÉIqùŸ˘+2&∏ Àù.…‚ƒœ3E’Oi—‰:>ͤĹ
  416. =Õec=ĂŤR˝”eĂą=<V$ì˙+x+¢ïÒÕ<Ă eWĂĽÂť–˚∫Õ §&ÂŁĂ  ]fPA´âtĂŤnöå∏◊ó „Ë@∆≠´ĂˇË˜}a_CI˚ŠyòHg,Ă´SSVĂŹBƒl4 L.ÈY…á,2∂íäÙ.$ó¸¤Ĺ¸*€óy
  417. π?G,ˆšÂˇĂ†ĂŽĂ§=^Vkvo¹ó{§ƒ2¹¨ÏüoÍD-ãÊ ó¼cVÙ\'™G~\'p¢%* ã˚÷
  418. ÂŞÂşnh˚ºO^∏…®[Ó“‚ÅfıÌ≥∫F!“(π∑T6`ÂŹtΩÆ0ĂŹÂťrTÎ`»Ñ«
  419. ]Ōp˝)=¿Ô0∆öV‡ˆ„ø~¯ÁÔ∏b*fc»‡Îı„Ú}∆“ˆ‚ˆŤĂœ†˙ˆ~<ÿ·Ù vĂŠ1‹pÂżTD∆ÔîÄ“úhˆ*Ú€îe)K –¨Ăš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;” ˆŤkÔˇflTæ∑óflË” ÆC©Ô[≥◊ËšÂ¨hĂŞ"ÆbF?Ăş%h˙ˇ4xèÕ(Ăł2ÙáíM])Ñd|=fĂŤ-cI0ĂąL¢kÖêk‰Rƒ«ıÄWĂą8mO3∏&√æËXÂŻHĂł—ì]yF2»–˜ádàà‡‹Çο„≥7mÂŞHAS∑¶.;Œx(1} _kdŠ.dç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Ĺ‚PdĂŞĂŁh˘ßHVç5ȂŹĂ§ĂŒĂ›§Ă–/M=gĂŤ¾¹ÿGĂť1coÔuñæ‘zÂŽ. õ∑7ÉÏÜÆ,°’€ ĂĂ‰ĂŒâˆ‚7e º® íˆ⁄◊øNWK”ÂYµ‚ñé;¾œgV-fl>ÂľtË¥áßN2 ÂŻÂśBaP-)eW.Ă Ă´t^∏1›C∑Ö?€ž&”5’4jvã–ªZ á+4% ´0€ŚÂťĂş^°´Š Ýiπ∑é®óܱÒÿ‰ïˆÌ–†â—ŠĂ†19rQ=Í|ı•rMĂŚÂŹ;ò‰€°ĂŠ9.” ‹˝V«ã¯∏,+ĂŤÂŽj*¥¡/';
  420. $model = new AppModel(array('name' => 'BinaryTest', 'ds' => 'test'));
  421. $model->save(compact('data'));
  422. $result = $model->find('first');
  423. $this->assertEquals($data, $result['BinaryTest']['data']);
  424. }
  425. /**
  426. * Tests passing PostgreSQL regular expression operators when building queries
  427. *
  428. * @return void
  429. */
  430. public function testRegexpOperatorConditionsParsing() {
  431. $this->assertSame(' WHERE "name" ~ \'[a-z_]+\'', $this->Dbo->conditions(array('name ~' => '[a-z_]+')));
  432. $this->assertSame(' WHERE "name" ~* \'[a-z_]+\'', $this->Dbo->conditions(array('name ~*' => '[a-z_]+')));
  433. $this->assertSame(' WHERE "name" !~ \'[a-z_]+\'', $this->Dbo->conditions(array('name !~' => '[a-z_]+')));
  434. $this->assertSame(' WHERE "name" !~* \'[a-z_]+\'', $this->Dbo->conditions(array('name !~*' => '[a-z_]+')));
  435. }
  436. /**
  437. * Tests the syntax of generated schema indexes
  438. *
  439. * @return void
  440. */
  441. public function testSchemaIndexSyntax() {
  442. $schema = new CakeSchema();
  443. $schema->tables = array('i18n' => array(
  444. 'id' => array(
  445. 'type' => 'integer', 'null' => false, 'default' => null,
  446. 'length' => 10, 'key' => 'primary'
  447. ),
  448. 'locale' => array('type' => 'string', 'null' => false, 'length' => 6, 'key' => 'index'),
  449. 'model' => array('type' => 'string', 'null' => false, 'key' => 'index'),
  450. 'foreign_key' => array(
  451. 'type' => 'integer', 'null' => false, 'length' => 10, 'key' => 'index'
  452. ),
  453. 'field' => array('type' => 'string', 'null' => false, 'key' => 'index'),
  454. 'content' => array('type' => 'text', 'null' => true, 'default' => null),
  455. 'indexes' => array(
  456. 'PRIMARY' => array('column' => 'id', 'unique' => 1),
  457. 'locale' => array('column' => 'locale', 'unique' => 0),
  458. 'model' => array('column' => 'model', 'unique' => 0),
  459. 'row_id' => array('column' => 'foreign_key', 'unique' => 0),
  460. 'field' => array('column' => 'field', 'unique' => 0)
  461. )
  462. ));
  463. $result = $this->Dbo->createSchema($schema);
  464. $this->assertNotRegExp('/^CREATE INDEX(.+);,$/', $result);
  465. }
  466. /**
  467. * testCakeSchema method
  468. *
  469. * Test that schema generated postgresql queries are valid. ref #5696
  470. * Check that the create statement for a schema generated table is the same as the original sql
  471. *
  472. * @return void
  473. */
  474. public function testCakeSchema() {
  475. $db1 = ConnectionManager::getDataSource('test');
  476. $db1->cacheSources = false;
  477. $db1->rawQuery('CREATE TABLE ' . $db1->fullTableName('datatype_tests') . ' (
  478. id serial NOT NULL,
  479. "varchar" character varying(40) NOT NULL,
  480. "full_length" character varying NOT NULL,
  481. "huge_int" bigint NOT NULL,
  482. "timestamp" timestamp without time zone,
  483. "date" date,
  484. CONSTRAINT test_data_types_pkey PRIMARY KEY (id)
  485. )');
  486. $schema = new CakeSchema(array('connection' => 'test'));
  487. $result = $schema->read(array(
  488. 'connection' => 'test',
  489. 'models' => array('DatatypeTest')
  490. ));
  491. $schema->tables = array(
  492. 'datatype_tests' => $result['tables']['missing']['datatype_tests']
  493. );
  494. $result = $db1->createSchema($schema, 'datatype_tests');
  495. $this->assertNotRegExp('/timestamp DEFAULT/', $result);
  496. $this->assertRegExp('/\"full_length\"\s*text\s.*,/', $result);
  497. $this->assertContains('timestamp ,', $result);
  498. $this->assertContains('"huge_int" bigint NOT NULL,', $result);
  499. $db1->query('DROP TABLE ' . $db1->fullTableName('datatype_tests'));
  500. $db1->query($result);
  501. $result2 = $schema->read(array(
  502. 'connection' => 'test',
  503. 'models' => array('DatatypeTest')
  504. ));
  505. $schema->tables = array('datatype_tests' => $result2['tables']['missing']['datatype_tests']);
  506. $result2 = $db1->createSchema($schema, 'datatype_tests');
  507. $this->assertEquals($result, $result2);
  508. $db1->query('DROP TABLE ' . $db1->fullTableName('datatype_tests'));
  509. }
  510. /**
  511. * testCakeSchemaBegserial method
  512. *
  513. * Test that schema generated postgresql queries are valid.
  514. *
  515. * @return void
  516. */
  517. public function testCakeSchemaBigserial() {
  518. $db1 = ConnectionManager::getDataSource('test');
  519. $db1->cacheSources = false;
  520. $db1->rawQuery('CREATE TABLE ' . $db1->fullTableName('bigserial_tests') . ' (
  521. "id" bigserial NOT NULL,
  522. "varchar" character varying(40) NOT NULL,
  523. PRIMARY KEY ("id")
  524. )');
  525. $schema = new CakeSchema(array('connection' => 'test'));
  526. $result = $schema->read(array(
  527. 'connection' => 'test',
  528. 'models' => array('BigserialTest')
  529. ));
  530. $schema->tables = array(
  531. 'bigserial_tests' => $result['tables']['missing']['bigserial_tests']
  532. );
  533. $result = $db1->createSchema($schema, 'bigserial_tests');
  534. $this->assertContains('"id" bigserial NOT NULL,', $result);
  535. $db1->query('DROP TABLE ' . $db1->fullTableName('bigserial_tests'));
  536. }
  537. /**
  538. * Test index generation from table info.
  539. *
  540. * @return void
  541. */
  542. public function testIndexGeneration() {
  543. $name = $this->Dbo->fullTableName('index_test', false, false);
  544. $this->Dbo->query('CREATE TABLE ' . $name . ' ("id" serial NOT NULL PRIMARY KEY, "bool" integer, "small_char" varchar(50), "description" varchar(40) )');
  545. $this->Dbo->query('CREATE INDEX pointless_bool ON ' . $name . '("bool")');
  546. $this->Dbo->query('CREATE UNIQUE INDEX char_index ON ' . $name . '("small_char")');
  547. $expected = array(
  548. 'PRIMARY' => array('unique' => true, 'column' => 'id'),
  549. 'pointless_bool' => array('unique' => false, 'column' => 'bool'),
  550. 'char_index' => array('unique' => true, 'column' => 'small_char'),
  551. );
  552. $result = $this->Dbo->index($name);
  553. $this->Dbo->query('DROP TABLE ' . $name);
  554. $this->assertEquals($expected, $result);
  555. $name = $this->Dbo->fullTableName('index_test_2', false, false);
  556. $this->Dbo->query('CREATE TABLE ' . $name . ' ("id" serial NOT NULL PRIMARY KEY, "bool" integer, "small_char" varchar(50), "description" varchar(40) )');
  557. $this->Dbo->query('CREATE UNIQUE INDEX multi_col ON ' . $name . '("small_char", "bool")');
  558. $expected = array(
  559. 'PRIMARY' => array('unique' => true, 'column' => 'id'),
  560. 'multi_col' => array('unique' => true, 'column' => array('small_char', 'bool')),
  561. );
  562. $result = $this->Dbo->index($name);
  563. $this->Dbo->query('DROP TABLE ' . $name);
  564. $this->assertEquals($expected, $result);
  565. }
  566. /**
  567. * Test the alterSchema capabilities of postgres
  568. *
  569. * @return void
  570. */
  571. public function testAlterSchema() {
  572. $Old = new CakeSchema(array(
  573. 'connection' => 'test',
  574. 'name' => 'AlterPosts',
  575. 'alter_posts' => array(
  576. 'id' => array('type' => 'integer', 'key' => 'primary'),
  577. 'author_id' => array('type' => 'integer', 'null' => false),
  578. 'title' => array('type' => 'string', 'null' => true),
  579. 'body' => array('type' => 'text'),
  580. 'published' => array('type' => 'string', 'length' => 1, 'default' => 'N'),
  581. 'created' => array('type' => 'datetime'),
  582. 'updated' => array('type' => 'datetime'),
  583. )
  584. ));
  585. $this->Dbo->query($this->Dbo->createSchema($Old));
  586. $New = new CakeSchema(array(
  587. 'connection' => 'test',
  588. 'name' => 'AlterPosts',
  589. 'alter_posts' => array(
  590. 'id' => array('type' => 'integer', 'key' => 'primary'),
  591. 'author_id' => array('type' => 'integer', 'null' => true),
  592. 'title' => array('type' => 'string', 'null' => false, 'default' => 'my title'),
  593. 'body' => array('type' => 'string', 'length' => 500),
  594. 'status' => array('type' => 'integer', 'length' => 3, 'default' => 1),
  595. 'created' => array('type' => 'datetime'),
  596. 'updated' => array('type' => 'datetime'),
  597. )
  598. ));
  599. $this->Dbo->query($this->Dbo->alterSchema($New->compare($Old), 'alter_posts'));
  600. $model = new CakeTestModel(array('table' => 'alter_posts', 'ds' => 'test'));
  601. $result = $model->schema();
  602. $this->assertTrue(isset($result['status']));
  603. $this->assertFalse(isset($result['published']));
  604. $this->assertEquals('string', $result['body']['type']);
  605. $this->assertEquals(1, $result['status']['default']);
  606. $this->assertEquals(true, $result['author_id']['null']);
  607. $this->assertEquals(false, $result['title']['null']);
  608. $this->Dbo->query($this->Dbo->dropSchema($New));
  609. $New = new CakeSchema(array(
  610. 'connection' => 'test_suite',
  611. 'name' => 'AlterPosts',
  612. 'alter_posts' => array(
  613. 'id' => array('type' => 'string', 'length' => 36, 'key' => 'primary'),
  614. 'author_id' => array('type' => 'integer', 'null' => false),
  615. 'title' => array('type' => 'string', 'null' => true),
  616. 'body' => array('type' => 'text'),
  617. 'published' => array('type' => 'string', 'length' => 1, 'default' => 'N'),
  618. 'created' => array('type' => 'datetime'),
  619. 'updated' => array('type' => 'datetime'),
  620. )
  621. ));
  622. $result = $this->Dbo->alterSchema($New->compare($Old), 'alter_posts');
  623. $this->assertNotRegExp('/varchar\(36\) NOT NULL/i', $result);
  624. }
  625. /**
  626. * Test the alterSchema changing boolean to integer
  627. *
  628. * @return void
  629. */
  630. public function testAlterSchemaBooleanToIntegerField() {
  631. $default = array(
  632. 'connection' => 'test',
  633. 'name' => 'BoolField',
  634. 'bool_fields' => array(
  635. 'id' => array('type' => 'integer', 'key' => 'primary'),
  636. 'name' => array('type' => 'string', 'length' => 50),
  637. 'active' => array('type' => 'boolean', 'null' => false),
  638. )
  639. );
  640. $Old = new CakeSchema($default);
  641. $result = $this->Dbo->query($this->Dbo->createSchema($Old));
  642. $this->assertTrue($result);
  643. $modified = $default;
  644. $modified['bool_fields']['active'] = array('type' => 'integer', 'null' => true);
  645. $New = new CakeSchema($modified);
  646. $query = $this->Dbo->alterSchema($New->compare($Old));
  647. $result = $this->Dbo->query($query);
  648. $this->Dbo->query($this->Dbo->dropSchema($Old));
  649. }
  650. /**
  651. * Test the alterSchema changing text to integer
  652. *
  653. * @return void
  654. */
  655. public function testAlterSchemaTextToIntegerField() {
  656. $default = array(
  657. 'connection' => 'test',
  658. 'name' => 'TextField',
  659. 'text_fields' => array(
  660. 'id' => array('type' => 'integer', 'key' => 'primary'),
  661. 'name' => array('type' => 'string', 'length' => 50),
  662. 'active' => array('type' => 'text', 'null' => false),
  663. )
  664. );
  665. $Old = new CakeSchema($default);
  666. $result = $this->Dbo->query($this->Dbo->createSchema($Old));
  667. $this->assertTrue($result);
  668. $modified = $default;
  669. $modified['text_fields']['active'] = array('type' => 'integer', 'null' => true);
  670. $New = new CakeSchema($modified);
  671. $this->Dbo->query($this->Dbo->alterSchema($New->compare($Old)));
  672. $result = $this->Dbo->describe('text_fields');
  673. $this->Dbo->query($this->Dbo->dropSchema($Old));
  674. $expected = array(
  675. 'type' => 'integer',
  676. 'null' => true,
  677. 'default' => null,
  678. 'length' => null,
  679. );
  680. $this->assertEquals($expected, $result['active']);
  681. }
  682. /**
  683. * Test the alter index capabilities of postgres
  684. *
  685. * @return void
  686. */
  687. public function testAlterIndexes() {
  688. $this->Dbo->cacheSources = false;
  689. $schema1 = new CakeSchema(array(
  690. 'name' => 'AlterTest1',
  691. 'connection' => 'test',
  692. 'altertest' => array(
  693. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  694. 'name' => array('type' => 'string', 'null' => false, 'length' => 50),
  695. 'group1' => array('type' => 'integer', 'null' => true),
  696. 'group2' => array('type' => 'integer', 'null' => true)
  697. )
  698. ));
  699. $this->Dbo->rawQuery($this->Dbo->createSchema($schema1));
  700. $schema2 = new CakeSchema(array(
  701. 'name' => 'AlterTest2',
  702. 'connection' => 'test',
  703. 'altertest' => array(
  704. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  705. 'name' => array('type' => 'string', 'null' => false, 'length' => 50),
  706. 'group1' => array('type' => 'integer', 'null' => true),
  707. 'group2' => array('type' => 'integer', 'null' => true),
  708. 'indexes' => array(
  709. 'name_idx' => array('unique' => false, 'column' => 'name'),
  710. 'group_idx' => array('unique' => false, 'column' => 'group1'),
  711. 'compound_idx' => array('unique' => false, 'column' => array('group1', 'group2')),
  712. 'PRIMARY' => array('unique' => true, 'column' => 'id')
  713. )
  714. )
  715. ));
  716. $this->Dbo->query($this->Dbo->alterSchema($schema2->compare($schema1)));
  717. $indexes = $this->Dbo->index('altertest');
  718. $this->assertEquals($schema2->tables['altertest']['indexes'], $indexes);
  719. // Change three indexes, delete one and add another one
  720. $schema3 = new CakeSchema(array(
  721. 'name' => 'AlterTest3',
  722. 'connection' => 'test',
  723. 'altertest' => array(
  724. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  725. 'name' => array('type' => 'string', 'null' => false, 'length' => 50),
  726. 'group1' => array('type' => 'integer', 'null' => true),
  727. 'group2' => array('type' => 'integer', 'null' => true),
  728. 'indexes' => array(
  729. 'name_idx' => array('unique' => true, 'column' => 'name'),
  730. 'group_idx' => array('unique' => false, 'column' => 'group2'),
  731. 'compound_idx' => array('unique' => false, 'column' => array('group2', 'group1')),
  732. 'another_idx' => array('unique' => false, 'column' => array('group1', 'name')))
  733. )));
  734. $this->Dbo->query($this->Dbo->alterSchema($schema3->compare($schema2)));
  735. $indexes = $this->Dbo->index('altertest');
  736. $this->assertEquals($schema3->tables['altertest']['indexes'], $indexes);
  737. // Compare us to ourself.
  738. $this->assertEquals(array(), $schema3->compare($schema3));
  739. // Drop the indexes
  740. $this->Dbo->query($this->Dbo->alterSchema($schema1->compare($schema3)));
  741. $indexes = $this->Dbo->index('altertest');
  742. $this->assertEquals(array(), $indexes);
  743. $this->Dbo->query($this->Dbo->dropSchema($schema1));
  744. }
  745. /**
  746. * Test the alterSchema RENAME statements
  747. *
  748. * @return void
  749. */
  750. public function testAlterSchemaRenameTo() {
  751. $query = $this->Dbo->alterSchema(array(
  752. 'posts' => array(
  753. 'change' => array(
  754. 'title' => array('name' => 'subject', 'type' => 'string', 'null' => false)
  755. )
  756. )
  757. ));
  758. $this->assertContains('RENAME "title" TO "subject";', $query);
  759. $this->assertContains('ALTER COLUMN "subject" TYPE', $query);
  760. $this->assertNotContains(";\n\tALTER COLUMN \"subject\" TYPE", $query);
  761. $this->assertNotContains('ALTER COLUMN "title" TYPE "subject"', $query);
  762. }
  763. /**
  764. * Test it is possible to use virtual field with postgresql
  765. *
  766. * @return void
  767. */
  768. public function testVirtualFields() {
  769. $this->loadFixtures('Article', 'Comment', 'User', 'Attachment', 'Tag', 'ArticlesTag');
  770. $Article = new Article;
  771. $Article->virtualFields = array(
  772. 'next_id' => 'Article.id + 1',
  773. 'complex' => 'Article.title || Article.body',
  774. 'functional' => 'COALESCE(User.user, Article.title)',
  775. 'subquery' => 'SELECT count(*) FROM ' . $Article->Comment->table
  776. );
  777. $result = $Article->find('first');
  778. $this->assertEquals(2, $result['Article']['next_id']);
  779. $this->assertEquals($result['Article']['complex'], $result['Article']['title'] . $result['Article']['body']);
  780. $this->assertEquals($result['Article']['functional'], $result['User']['user']);
  781. $this->assertEquals(6, $result['Article']['subquery']);
  782. }
  783. /**
  784. * Test that virtual fields work with SQL constants
  785. *
  786. * @return void
  787. */
  788. public function testVirtualFieldAsAConstant() {
  789. $this->loadFixtures('Article', 'Comment');
  790. $Article = ClassRegistry::init('Article');
  791. $Article->virtualFields = array(
  792. 'empty' => "NULL",
  793. 'number' => 43,
  794. 'truth' => 'TRUE'
  795. );
  796. $result = $Article->find('first');
  797. $this->assertNull($result['Article']['empty']);
  798. $this->assertTrue($result['Article']['truth']);
  799. $this->assertEquals(43, $result['Article']['number']);
  800. }
  801. /**
  802. * Tests additional order options for postgres
  803. *
  804. * @return void
  805. */
  806. public function testOrderAdditionalParams() {
  807. $result = $this->Dbo->order(array('title' => 'DESC NULLS FIRST', 'body' => 'DESC'));
  808. $expected = ' ORDER BY "title" DESC NULLS FIRST, "body" DESC';
  809. $this->assertEquals($expected, $result);
  810. }
  811. /**
  812. * Test it is possible to do a SELECT COUNT(DISTINCT Model.field)
  813. * query in postgres and it gets correctly quoted
  814. *
  815. * @return void
  816. */
  817. public function testQuoteDistinctInFunction() {
  818. $this->loadFixtures('Article');
  819. $Article = new Article;
  820. $result = $this->Dbo->fields($Article, null, array('COUNT(DISTINCT Article.id)'));
  821. $expected = array('COUNT(DISTINCT "Article"."id")');
  822. $this->assertEquals($expected, $result);
  823. $result = $this->Dbo->fields($Article, null, array('COUNT(DISTINCT id)'));
  824. $expected = array('COUNT(DISTINCT "id")');
  825. $this->assertEquals($expected, $result);
  826. $result = $this->Dbo->fields($Article, null, array('COUNT(DISTINCT FUNC(id))'));
  827. $expected = array('COUNT(DISTINCT FUNC("id"))');
  828. $this->assertEquals($expected, $result);
  829. }
  830. /**
  831. * test that saveAll works even with conditions that lack a model name.
  832. *
  833. * @return void
  834. */
  835. public function testUpdateAllWithNonQualifiedConditions() {
  836. $this->loadFixtures('Article');
  837. $Article = new Article();
  838. $result = $Article->updateAll(array('title' => "'Awesome'"), array('title' => 'Third Article'));
  839. $this->assertTrue($result);
  840. $result = $Article->find('count', array(
  841. 'conditions' => array('Article.title' => 'Awesome')
  842. ));
  843. $this->assertEquals(1, $result, 'Article count is wrong or fixture has changed.');
  844. }
  845. /**
  846. * test alterSchema on two tables.
  847. *
  848. * @return void
  849. */
  850. public function testAlteringTwoTables() {
  851. $schema1 = new CakeSchema(array(
  852. 'name' => 'AlterTest1',
  853. 'connection' => 'test',
  854. 'altertest' => array(
  855. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  856. 'name' => array('type' => 'string', 'null' => false, 'length' => 50),
  857. ),
  858. 'other_table' => array(
  859. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  860. 'name' => array('type' => 'string', 'null' => false, 'length' => 50),
  861. )
  862. ));
  863. $schema2 = new CakeSchema(array(
  864. 'name' => 'AlterTest1',
  865. 'connection' => 'test',
  866. 'altertest' => array(
  867. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  868. 'field_two' => array('type' => 'string', 'null' => false, 'length' => 50),
  869. ),
  870. 'other_table' => array(
  871. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  872. 'field_two' => array('type' => 'string', 'null' => false, 'length' => 50),
  873. )
  874. ));
  875. $result = $this->db->alterSchema($schema2->compare($schema1));
  876. $this->assertEquals(2, substr_count($result, 'field_two'), 'Too many fields');
  877. $this->assertFalse(strpos(';ALTER', $result), 'Too many semi colons');
  878. }
  879. /**
  880. * test encoding setting.
  881. *
  882. * @return void
  883. */
  884. public function testEncoding() {
  885. $result = $this->Dbo->setEncoding('UTF8');
  886. $this->assertTrue($result);
  887. $result = $this->Dbo->getEncoding();
  888. $this->assertEquals('UTF8', $result);
  889. $result = $this->Dbo->setEncoding('EUC_JP'); /* 'EUC_JP' is right character code name in PostgreSQL */
  890. $this->assertTrue($result);
  891. $result = $this->Dbo->getEncoding();
  892. $this->assertEquals('EUC_JP', $result);
  893. }
  894. /**
  895. * Test truncate with a mock.
  896. *
  897. * @return void
  898. */
  899. public function testTruncateStatements() {
  900. $this->loadFixtures('Article', 'User');
  901. $db = ConnectionManager::getDatasource('test');
  902. $schema = $db->config['schema'];
  903. $Article = new Article();
  904. $this->Dbo = $this->getMock('Postgres', array('execute'), array($db->config));
  905. $this->Dbo->expects($this->at(0))->method('execute')
  906. ->with("DELETE FROM \"$schema\".\"articles\"");
  907. $this->Dbo->truncate($Article);
  908. $this->Dbo->expects($this->at(0))->method('execute')
  909. ->with("DELETE FROM \"$schema\".\"articles\"");
  910. $this->Dbo->truncate('articles');
  911. // #2355: prevent duplicate prefix
  912. $this->Dbo->config['prefix'] = 'tbl_';
  913. $Article->tablePrefix = 'tbl_';
  914. $this->Dbo->expects($this->at(0))->method('execute')
  915. ->with("DELETE FROM \"$schema\".\"tbl_articles\"");
  916. $this->Dbo->truncate($Article);
  917. $this->Dbo->expects($this->at(0))->method('execute')
  918. ->with("DELETE FROM \"$schema\".\"tbl_articles\"");
  919. $this->Dbo->truncate('articles');
  920. }
  921. /**
  922. * Test nested transaction
  923. *
  924. * @return void
  925. */
  926. public function testNestedTransaction() {
  927. $this->Dbo->useNestedTransactions = true;
  928. $this->skipIf($this->Dbo->nestedTransactionSupported() === false, 'The Postgres server do not support nested transaction');
  929. $this->loadFixtures('Article');
  930. $model = new Article();
  931. $model->hasOne = $model->hasMany = $model->belongsTo = $model->hasAndBelongsToMany = array();
  932. $model->cacheQueries = false;
  933. $this->Dbo->cacheMethods = false;
  934. $this->assertTrue($this->Dbo->begin());
  935. $this->assertNotEmpty($model->read(null, 1));
  936. $this->assertTrue($this->Dbo->begin());
  937. $this->assertTrue($model->delete(1));
  938. $this->assertEmpty($model->read(null, 1));
  939. $this->assertTrue($this->Dbo->rollback());
  940. $this->assertNotEmpty($model->read(null, 1));
  941. $this->assertTrue($this->Dbo->begin());
  942. $this->assertTrue($model->delete(1));
  943. $this->assertEmpty($model->read(null, 1));
  944. $this->assertTrue($this->Dbo->commit());
  945. $this->assertEmpty($model->read(null, 1));
  946. $this->assertTrue($this->Dbo->rollback());
  947. $this->assertNotEmpty($model->read(null, 1));
  948. }
  949. public function testResetSequence() {
  950. $model = new Article();
  951. $table = $this->Dbo->fullTableName($model, false);
  952. $fields = array(
  953. 'id', 'user_id', 'title', 'body', 'published',
  954. );
  955. $values = array(
  956. array(1, 1, 'test', 'first post', false),
  957. array(2, 1, 'test 2', 'second post post', false),
  958. );
  959. $this->Dbo->insertMulti($table, $fields, $values);
  960. $sequence = $this->Dbo->getSequence($table);
  961. $result = $this->Dbo->rawQuery("SELECT nextval('$sequence')");
  962. $original = $result->fetch(PDO::FETCH_ASSOC);
  963. $this->assertTrue($this->Dbo->resetSequence($table, 'id'));
  964. $result = $this->Dbo->rawQuery("SELECT currval('$sequence')");
  965. $new = $result->fetch(PDO::FETCH_ASSOC);
  966. $this->assertTrue($new['currval'] > $original['nextval'], 'Sequence did not update');
  967. }
  968. public function testSettings() {
  969. Configure::write('Cache.disable', true);
  970. $this->Dbo = ConnectionManager::getDataSource('test');
  971. $this->skipIf(!($this->Dbo instanceof Postgres));
  972. $config2 = $this->Dbo->config;
  973. $config2['settings']['datestyle'] = 'sql, dmy';
  974. ConnectionManager::create('test2', $config2);
  975. $dbo2 = new Postgres($config2, true);
  976. $expected = array(array('r' => date('d/m/Y')));
  977. $r = $dbo2->fetchRow('SELECT now()::date AS "r"');
  978. $this->assertEquals($expected, $r);
  979. $dbo2->execute('SET DATESTYLE TO ISO');
  980. $dbo2->disconnect();
  981. }
  982. /**
  983. * Test the limit function.
  984. *
  985. * @return void
  986. */
  987. public function testLimit() {
  988. $db = $this->Dbo;
  989. $result = $db->limit('0');
  990. $this->assertNull($result);
  991. $result = $db->limit('10');
  992. $this->assertEquals(' LIMIT 10', $result);
  993. $result = $db->limit('FARTS', 'BOOGERS');
  994. $this->assertEquals(' LIMIT 0 OFFSET 0', $result);
  995. $result = $db->limit(20, 10);
  996. $this->assertEquals(' LIMIT 20 OFFSET 10', $result);
  997. $result = $db->limit(10, 300000000000000000000000000000);
  998. $scientificNotation = sprintf('%.1E', 300000000000000000000000000000);
  999. $this->assertNotContains($scientificNotation, $result);
  1000. }
  1001. /**
  1002. * Test that postgres describes UUID columns correctly.
  1003. *
  1004. * @return void
  1005. */
  1006. public function testDescribeUuid() {
  1007. $db = $this->Dbo;
  1008. $db->execute('CREATE TABLE test_uuid_describe (id UUID PRIMARY KEY, name VARCHAR(255))');
  1009. $data = $db->describe('test_uuid_describe');
  1010. $expected = array(
  1011. 'type' => 'string',
  1012. 'null' => false,
  1013. 'default' => null,
  1014. 'length' => 36,
  1015. );
  1016. $this->assertSame($expected, $data['id']);
  1017. $db->execute('DROP TABLE test_uuid_describe');
  1018. }
  1019. /**
  1020. * Test describe() behavior for timestamp columns.
  1021. *
  1022. * @return void
  1023. */
  1024. public function testDescribeTimestamp() {
  1025. $this->loadFixtures('User');
  1026. $model = ClassRegistry::init('User');
  1027. $result = $this->Dbo->describe($model);
  1028. $expected = array(
  1029. 'id' => array(
  1030. 'type' => 'integer',
  1031. 'null' => false,
  1032. 'default' => null,
  1033. 'length' => 11,
  1034. 'key' => 'primary'
  1035. ),
  1036. 'user' => array(
  1037. 'type' => 'string',
  1038. 'null' => true,
  1039. 'default' => null,
  1040. 'length' => 255
  1041. ),
  1042. 'password' => array(
  1043. 'type' => 'string',
  1044. 'null' => true,
  1045. 'default' => null,
  1046. 'length' => 255
  1047. ),
  1048. 'created' => array(
  1049. 'type' => 'datetime',
  1050. 'null' => true,
  1051. 'default' => null,
  1052. 'length' => null
  1053. ),
  1054. 'updated' => array(
  1055. 'type' => 'datetime',
  1056. 'null' => true,
  1057. 'default' => null,
  1058. 'length' => null
  1059. )
  1060. );
  1061. $this->assertEquals($expected, $result);
  1062. }
  1063. }