PostgresTest.php 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167
  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ì€∆Ω„WÃ%)nï0¯îâ-«é]Q"πXµáÿ•Ip - P V,]Ú#c˚ˇ‰ut¥†∏Ti9 Ü=”›Ø_˜4>à∑‚Épcé¢Pxæ®2q\'
  408. 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
  409. ˛§¯ˇ:-˜ò7€ÓFæ∂∑Õ˛∆“V’>ı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•/f∑j£
  412. dw"IÊÜπ<ôÿˆ%IG1ytÛDflXg|Éòa§˜}C˛¿ÿe°G´Ú±jÍm~¿/∂hã<#-¥•ıùe87€t˜õ6w}´{æ
  413. m‹ê– ∆¡ 6⁄\
  414. rAÀBùZ3aË‚r$G·$ó0Ñ üâUY4È™¡%C∑Ÿ2rc<Iõ-cï.
  415. [ŒöâFA†É‡+QglMÉîÉÄúÌ|¸»#x7¥«MgVÎ-GGÚ• I?Á‘”Lzw∞pHů◊nefqCî.nÕeè∆ÿÛy¡˙fb≤üŒHÜAëÕNq=´@ ’cQdÖúAÉIqñŸ˘+2&∏ Àù.gÅ‚ƒœ3EPƒOi—‰:>ÍCäı
  416. =Õec=ëR˝”eñ=<V$ì˙+x+¢ïÒÕ<àeWå»–˚∫Õ d§&£àf ]fPA´âtënöå∏◊ó „Ë@∆≠K´÷˘}a_CI˚©yòHg,ôSSVìBƒl4 L.ÈY…á,2∂íäÙ.$ó¸CäŸ*€óy
  417. π?G,_√·ÆÎç=^Vkvo±ó{§ƒ2»±¨Ïüo»ëD-ãé fió¥cVÙ\'™G~\'p¢%* ã˚÷
  418. ªºnh˚ºO^∏…®[Ó“‚ÅfıÌ≥∫F!Eœ(π∑T6`¬tΩÆ0ì»rTÎ`»Ñ«
  419. ]≈å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*¡·/';
  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 alter index capabilities of postgres
  652. *
  653. * @return void
  654. */
  655. public function testAlterIndexes() {
  656. $this->Dbo->cacheSources = false;
  657. $schema1 = new CakeSchema(array(
  658. 'name' => 'AlterTest1',
  659. 'connection' => 'test',
  660. 'altertest' => array(
  661. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  662. 'name' => array('type' => 'string', 'null' => false, 'length' => 50),
  663. 'group1' => array('type' => 'integer', 'null' => true),
  664. 'group2' => array('type' => 'integer', 'null' => true)
  665. )
  666. ));
  667. $this->Dbo->rawQuery($this->Dbo->createSchema($schema1));
  668. $schema2 = new CakeSchema(array(
  669. 'name' => 'AlterTest2',
  670. 'connection' => 'test',
  671. 'altertest' => array(
  672. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  673. 'name' => array('type' => 'string', 'null' => false, 'length' => 50),
  674. 'group1' => array('type' => 'integer', 'null' => true),
  675. 'group2' => array('type' => 'integer', 'null' => true),
  676. 'indexes' => array(
  677. 'name_idx' => array('unique' => false, 'column' => 'name'),
  678. 'group_idx' => array('unique' => false, 'column' => 'group1'),
  679. 'compound_idx' => array('unique' => false, 'column' => array('group1', 'group2')),
  680. 'PRIMARY' => array('unique' => true, 'column' => 'id')
  681. )
  682. )
  683. ));
  684. $this->Dbo->query($this->Dbo->alterSchema($schema2->compare($schema1)));
  685. $indexes = $this->Dbo->index('altertest');
  686. $this->assertEquals($schema2->tables['altertest']['indexes'], $indexes);
  687. // Change three indexes, delete one and add another one
  688. $schema3 = new CakeSchema(array(
  689. 'name' => 'AlterTest3',
  690. 'connection' => 'test',
  691. 'altertest' => array(
  692. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  693. 'name' => array('type' => 'string', 'null' => false, 'length' => 50),
  694. 'group1' => array('type' => 'integer', 'null' => true),
  695. 'group2' => array('type' => 'integer', 'null' => true),
  696. 'indexes' => array(
  697. 'name_idx' => array('unique' => true, 'column' => 'name'),
  698. 'group_idx' => array('unique' => false, 'column' => 'group2'),
  699. 'compound_idx' => array('unique' => false, 'column' => array('group2', 'group1')),
  700. 'another_idx' => array('unique' => false, 'column' => array('group1', 'name')))
  701. )));
  702. $this->Dbo->query($this->Dbo->alterSchema($schema3->compare($schema2)));
  703. $indexes = $this->Dbo->index('altertest');
  704. $this->assertEquals($schema3->tables['altertest']['indexes'], $indexes);
  705. // Compare us to ourself.
  706. $this->assertEquals(array(), $schema3->compare($schema3));
  707. // Drop the indexes
  708. $this->Dbo->query($this->Dbo->alterSchema($schema1->compare($schema3)));
  709. $indexes = $this->Dbo->index('altertest');
  710. $this->assertEquals(array(), $indexes);
  711. $this->Dbo->query($this->Dbo->dropSchema($schema1));
  712. }
  713. /**
  714. * Test the alterSchema RENAME statements
  715. *
  716. * @return void
  717. */
  718. public function testAlterSchemaRenameTo() {
  719. $query = $this->Dbo->alterSchema(array(
  720. 'posts' => array(
  721. 'change' => array(
  722. 'title' => array('name' => 'subject', 'type' => 'string', 'null' => false)
  723. )
  724. )
  725. ));
  726. $this->assertContains('RENAME "title" TO "subject";', $query);
  727. $this->assertContains('ALTER COLUMN "subject" TYPE', $query);
  728. $this->assertNotContains(";\n\tALTER COLUMN \"subject\" TYPE", $query);
  729. $this->assertNotContains('ALTER COLUMN "title" TYPE "subject"', $query);
  730. }
  731. /**
  732. * Test it is possible to use virtual field with postgresql
  733. *
  734. * @return void
  735. */
  736. public function testVirtualFields() {
  737. $this->loadFixtures('Article', 'Comment', 'User', 'Attachment', 'Tag', 'ArticlesTag');
  738. $Article = new Article;
  739. $Article->virtualFields = array(
  740. 'next_id' => 'Article.id + 1',
  741. 'complex' => 'Article.title || Article.body',
  742. 'functional' => 'COALESCE(User.user, Article.title)',
  743. 'subquery' => 'SELECT count(*) FROM ' . $Article->Comment->table
  744. );
  745. $result = $Article->find('first');
  746. $this->assertEquals(2, $result['Article']['next_id']);
  747. $this->assertEquals($result['Article']['complex'], $result['Article']['title'] . $result['Article']['body']);
  748. $this->assertEquals($result['Article']['functional'], $result['User']['user']);
  749. $this->assertEquals(6, $result['Article']['subquery']);
  750. }
  751. /**
  752. * Test that virtual fields work with SQL constants
  753. *
  754. * @return void
  755. */
  756. public function testVirtualFieldAsAConstant() {
  757. $this->loadFixtures('Article', 'Comment');
  758. $Article = ClassRegistry::init('Article');
  759. $Article->virtualFields = array(
  760. 'empty' => "NULL",
  761. 'number' => 43,
  762. 'truth' => 'TRUE'
  763. );
  764. $result = $Article->find('first');
  765. $this->assertNull($result['Article']['empty']);
  766. $this->assertTrue($result['Article']['truth']);
  767. $this->assertEquals(43, $result['Article']['number']);
  768. }
  769. /**
  770. * Tests additional order options for postgres
  771. *
  772. * @return void
  773. */
  774. public function testOrderAdditionalParams() {
  775. $result = $this->Dbo->order(array('title' => 'DESC NULLS FIRST', 'body' => 'DESC'));
  776. $expected = ' ORDER BY "title" DESC NULLS FIRST, "body" DESC';
  777. $this->assertEquals($expected, $result);
  778. }
  779. /**
  780. * Test it is possible to do a SELECT COUNT(DISTINCT Model.field)
  781. * query in postgres and it gets correctly quoted
  782. *
  783. * @return void
  784. */
  785. public function testQuoteDistinctInFunction() {
  786. $this->loadFixtures('Article');
  787. $Article = new Article;
  788. $result = $this->Dbo->fields($Article, null, array('COUNT(DISTINCT Article.id)'));
  789. $expected = array('COUNT(DISTINCT "Article"."id")');
  790. $this->assertEquals($expected, $result);
  791. $result = $this->Dbo->fields($Article, null, array('COUNT(DISTINCT id)'));
  792. $expected = array('COUNT(DISTINCT "id")');
  793. $this->assertEquals($expected, $result);
  794. $result = $this->Dbo->fields($Article, null, array('COUNT(DISTINCT FUNC(id))'));
  795. $expected = array('COUNT(DISTINCT FUNC("id"))');
  796. $this->assertEquals($expected, $result);
  797. }
  798. /**
  799. * test that saveAll works even with conditions that lack a model name.
  800. *
  801. * @return void
  802. */
  803. public function testUpdateAllWithNonQualifiedConditions() {
  804. $this->loadFixtures('Article');
  805. $Article = new Article();
  806. $result = $Article->updateAll(array('title' => "'Awesome'"), array('title' => 'Third Article'));
  807. $this->assertTrue($result);
  808. $result = $Article->find('count', array(
  809. 'conditions' => array('Article.title' => 'Awesome')
  810. ));
  811. $this->assertEquals(1, $result, 'Article count is wrong or fixture has changed.');
  812. }
  813. /**
  814. * test alterSchema on two tables.
  815. *
  816. * @return void
  817. */
  818. public function testAlteringTwoTables() {
  819. $schema1 = new CakeSchema(array(
  820. 'name' => 'AlterTest1',
  821. 'connection' => 'test',
  822. 'altertest' => array(
  823. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  824. 'name' => array('type' => 'string', 'null' => false, 'length' => 50),
  825. ),
  826. 'other_table' => array(
  827. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  828. 'name' => array('type' => 'string', 'null' => false, 'length' => 50),
  829. )
  830. ));
  831. $schema2 = new CakeSchema(array(
  832. 'name' => 'AlterTest1',
  833. 'connection' => 'test',
  834. 'altertest' => array(
  835. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  836. 'field_two' => array('type' => 'string', 'null' => false, 'length' => 50),
  837. ),
  838. 'other_table' => array(
  839. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  840. 'field_two' => array('type' => 'string', 'null' => false, 'length' => 50),
  841. )
  842. ));
  843. $result = $this->db->alterSchema($schema2->compare($schema1));
  844. $this->assertEquals(2, substr_count($result, 'field_two'), 'Too many fields');
  845. $this->assertFalse(strpos(';ALTER', $result), 'Too many semi colons');
  846. }
  847. /**
  848. * test encoding setting.
  849. *
  850. * @return void
  851. */
  852. public function testEncoding() {
  853. $result = $this->Dbo->setEncoding('UTF8');
  854. $this->assertTrue($result);
  855. $result = $this->Dbo->getEncoding();
  856. $this->assertEquals('UTF8', $result);
  857. $result = $this->Dbo->setEncoding('EUC_JP'); /* 'EUC_JP' is right character code name in PostgreSQL */
  858. $this->assertTrue($result);
  859. $result = $this->Dbo->getEncoding();
  860. $this->assertEquals('EUC_JP', $result);
  861. }
  862. /**
  863. * Test truncate with a mock.
  864. *
  865. * @return void
  866. */
  867. public function testTruncateStatements() {
  868. $this->loadFixtures('Article', 'User');
  869. $db = ConnectionManager::getDatasource('test');
  870. $schema = $db->config['schema'];
  871. $Article = new Article();
  872. $this->Dbo = $this->getMock('Postgres', array('execute'), array($db->config));
  873. $this->Dbo->expects($this->at(0))->method('execute')
  874. ->with("DELETE FROM \"$schema\".\"articles\"");
  875. $this->Dbo->truncate($Article);
  876. $this->Dbo->expects($this->at(0))->method('execute')
  877. ->with("DELETE FROM \"$schema\".\"articles\"");
  878. $this->Dbo->truncate('articles');
  879. // #2355: prevent duplicate prefix
  880. $this->Dbo->config['prefix'] = 'tbl_';
  881. $Article->tablePrefix = 'tbl_';
  882. $this->Dbo->expects($this->at(0))->method('execute')
  883. ->with("DELETE FROM \"$schema\".\"tbl_articles\"");
  884. $this->Dbo->truncate($Article);
  885. $this->Dbo->expects($this->at(0))->method('execute')
  886. ->with("DELETE FROM \"$schema\".\"tbl_articles\"");
  887. $this->Dbo->truncate('articles');
  888. }
  889. /**
  890. * Test nested transaction
  891. *
  892. * @return void
  893. */
  894. public function testNestedTransaction() {
  895. $this->Dbo->useNestedTransactions = true;
  896. $this->skipIf($this->Dbo->nestedTransactionSupported() === false, 'The Postgres server do not support nested transaction');
  897. $this->loadFixtures('Article');
  898. $model = new Article();
  899. $model->hasOne = $model->hasMany = $model->belongsTo = $model->hasAndBelongsToMany = array();
  900. $model->cacheQueries = false;
  901. $this->Dbo->cacheMethods = false;
  902. $this->assertTrue($this->Dbo->begin());
  903. $this->assertNotEmpty($model->read(null, 1));
  904. $this->assertTrue($this->Dbo->begin());
  905. $this->assertTrue($model->delete(1));
  906. $this->assertEmpty($model->read(null, 1));
  907. $this->assertTrue($this->Dbo->rollback());
  908. $this->assertNotEmpty($model->read(null, 1));
  909. $this->assertTrue($this->Dbo->begin());
  910. $this->assertTrue($model->delete(1));
  911. $this->assertEmpty($model->read(null, 1));
  912. $this->assertTrue($this->Dbo->commit());
  913. $this->assertEmpty($model->read(null, 1));
  914. $this->assertTrue($this->Dbo->rollback());
  915. $this->assertNotEmpty($model->read(null, 1));
  916. }
  917. public function testResetSequence() {
  918. $model = new Article();
  919. $table = $this->Dbo->fullTableName($model, false);
  920. $fields = array(
  921. 'id', 'user_id', 'title', 'body', 'published',
  922. );
  923. $values = array(
  924. array(1, 1, 'test', 'first post', false),
  925. array(2, 1, 'test 2', 'second post post', false),
  926. );
  927. $this->Dbo->insertMulti($table, $fields, $values);
  928. $sequence = $this->Dbo->getSequence($table);
  929. $result = $this->Dbo->rawQuery("SELECT nextval('$sequence')");
  930. $original = $result->fetch(PDO::FETCH_ASSOC);
  931. $this->assertTrue($this->Dbo->resetSequence($table, 'id'));
  932. $result = $this->Dbo->rawQuery("SELECT currval('$sequence')");
  933. $new = $result->fetch(PDO::FETCH_ASSOC);
  934. $this->assertTrue($new['currval'] > $original['nextval'], 'Sequence did not update');
  935. }
  936. public function testSettings() {
  937. Configure::write('Cache.disable', true);
  938. $this->Dbo = ConnectionManager::getDataSource('test');
  939. $this->skipIf(!($this->Dbo instanceof Postgres));
  940. $config2 = $this->Dbo->config;
  941. $config2['settings']['datestyle'] = 'sql, dmy';
  942. ConnectionManager::create('test2', $config2);
  943. $dbo2 = new Postgres($config2, true);
  944. $expected = array(array('r' => date('d/m/Y')));
  945. $r = $dbo2->fetchRow('SELECT now()::date AS "r"');
  946. $this->assertEquals($expected, $r);
  947. $dbo2->execute('SET DATESTYLE TO ISO');
  948. $dbo2->disconnect();
  949. }
  950. /**
  951. * Test the limit function.
  952. *
  953. * @return void
  954. */
  955. public function testLimit() {
  956. $db = $this->Dbo;
  957. $result = $db->limit('0');
  958. $this->assertNull($result);
  959. $result = $db->limit('10');
  960. $this->assertEquals(' LIMIT 10', $result);
  961. $result = $db->limit('FARTS', 'BOOGERS');
  962. $this->assertEquals(' LIMIT 0 OFFSET 0', $result);
  963. $result = $db->limit(20, 10);
  964. $this->assertEquals(' LIMIT 20 OFFSET 10', $result);
  965. $result = $db->limit(10, 300000000000000000000000000000);
  966. $scientificNotation = sprintf('%.1E', 300000000000000000000000000000);
  967. $this->assertNotContains($scientificNotation, $result);
  968. }
  969. /**
  970. * Test that postgres describes UUID columns correctly.
  971. *
  972. * @return void
  973. */
  974. public function testDescribeUuid() {
  975. $db = $this->Dbo;
  976. $db->execute('CREATE TABLE test_uuid_describe (id UUID PRIMARY KEY, name VARCHAR(255))');
  977. $data = $db->describe('test_uuid_describe');
  978. $expected = array(
  979. 'type' => 'string',
  980. 'null' => false,
  981. 'default' => null,
  982. 'length' => 36,
  983. );
  984. $this->assertSame($expected, $data['id']);
  985. $db->execute('DROP TABLE test_uuid_describe');
  986. }
  987. /**
  988. * Test describe() behavior for timestamp columns.
  989. *
  990. * @return void
  991. */
  992. public function testDescribeTimestamp() {
  993. $this->loadFixtures('User');
  994. $model = ClassRegistry::init('User');
  995. $result = $this->Dbo->describe($model);
  996. $expected = array(
  997. 'id' => array(
  998. 'type' => 'integer',
  999. 'null' => false,
  1000. 'default' => null,
  1001. 'length' => 11,
  1002. 'key' => 'primary'
  1003. ),
  1004. 'user' => array(
  1005. 'type' => 'string',
  1006. 'null' => true,
  1007. 'default' => null,
  1008. 'length' => 255
  1009. ),
  1010. 'password' => array(
  1011. 'type' => 'string',
  1012. 'null' => true,
  1013. 'default' => null,
  1014. 'length' => 255
  1015. ),
  1016. 'created' => array(
  1017. 'type' => 'datetime',
  1018. 'null' => true,
  1019. 'default' => null,
  1020. 'length' => null
  1021. ),
  1022. 'updated' => array(
  1023. 'type' => 'datetime',
  1024. 'null' => true,
  1025. 'default' => null,
  1026. 'length' => null
  1027. )
  1028. );
  1029. $this->assertEquals($expected, $result);
  1030. }
  1031. }