PostgresTest.php 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098
  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 boolean
  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 boolean
  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' => '1', 'default' => '', 'length' => ''),
  149. 'updated' => array('type' => 'datetime', 'null' => '1', 'default' => '', '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 boolean
  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. */
  191. public function setUp() {
  192. parent::setUp();
  193. Configure::write('Cache.disable', true);
  194. $this->Dbo = ConnectionManager::getDataSource('test');
  195. $this->skipIf(!($this->Dbo instanceof Postgres));
  196. $this->Dbo2 = new DboPostgresTestDb($this->Dbo->config, false);
  197. $this->model = new PostgresTestModel();
  198. }
  199. /**
  200. * Sets up a Dbo class instance for testing
  201. *
  202. */
  203. public function tearDown() {
  204. parent::tearDown();
  205. Configure::write('Cache.disable', false);
  206. unset($this->Dbo2);
  207. }
  208. /**
  209. * Test field quoting method
  210. *
  211. */
  212. public function testFieldQuoting() {
  213. $fields = array(
  214. '"PostgresTestModel"."id" AS "PostgresTestModel__id"',
  215. '"PostgresTestModel"."client_id" AS "PostgresTestModel__client_id"',
  216. '"PostgresTestModel"."name" AS "PostgresTestModel__name"',
  217. '"PostgresTestModel"."login" AS "PostgresTestModel__login"',
  218. '"PostgresTestModel"."passwd" AS "PostgresTestModel__passwd"',
  219. '"PostgresTestModel"."addr_1" AS "PostgresTestModel__addr_1"',
  220. '"PostgresTestModel"."addr_2" AS "PostgresTestModel__addr_2"',
  221. '"PostgresTestModel"."zip_code" AS "PostgresTestModel__zip_code"',
  222. '"PostgresTestModel"."city" AS "PostgresTestModel__city"',
  223. '"PostgresTestModel"."country" AS "PostgresTestModel__country"',
  224. '"PostgresTestModel"."phone" AS "PostgresTestModel__phone"',
  225. '"PostgresTestModel"."fax" AS "PostgresTestModel__fax"',
  226. '"PostgresTestModel"."url" AS "PostgresTestModel__url"',
  227. '"PostgresTestModel"."email" AS "PostgresTestModel__email"',
  228. '"PostgresTestModel"."comments" AS "PostgresTestModel__comments"',
  229. '"PostgresTestModel"."last_login" AS "PostgresTestModel__last_login"',
  230. '"PostgresTestModel"."created" AS "PostgresTestModel__created"',
  231. '"PostgresTestModel"."updated" AS "PostgresTestModel__updated"'
  232. );
  233. $result = $this->Dbo->fields($this->model);
  234. $expected = $fields;
  235. $this->assertEquals($expected, $result);
  236. $result = $this->Dbo->fields($this->model, null, 'PostgresTestModel.*');
  237. $expected = $fields;
  238. $this->assertEquals($expected, $result);
  239. $result = $this->Dbo->fields($this->model, null, array('*', 'AnotherModel.id', 'AnotherModel.name'));
  240. $expected = array_merge($fields, array(
  241. '"AnotherModel"."id" AS "AnotherModel__id"',
  242. '"AnotherModel"."name" AS "AnotherModel__name"'));
  243. $this->assertEquals($expected, $result);
  244. $result = $this->Dbo->fields($this->model, null, array('*', 'PostgresClientTestModel.*'));
  245. $expected = array_merge($fields, array(
  246. '"PostgresClientTestModel"."id" AS "PostgresClientTestModel__id"',
  247. '"PostgresClientTestModel"."name" AS "PostgresClientTestModel__name"',
  248. '"PostgresClientTestModel"."email" AS "PostgresClientTestModel__email"',
  249. '"PostgresClientTestModel"."created" AS "PostgresClientTestModel__created"',
  250. '"PostgresClientTestModel"."updated" AS "PostgresClientTestModel__updated"'));
  251. $this->assertEquals($expected, $result);
  252. }
  253. /**
  254. * testColumnParsing method
  255. *
  256. * @return void
  257. */
  258. public function testColumnParsing() {
  259. $this->assertEquals('text', $this->Dbo2->column('text'));
  260. $this->assertEquals('date', $this->Dbo2->column('date'));
  261. $this->assertEquals('boolean', $this->Dbo2->column('boolean'));
  262. $this->assertEquals('string', $this->Dbo2->column('character varying'));
  263. $this->assertEquals('time', $this->Dbo2->column('time without time zone'));
  264. $this->assertEquals('datetime', $this->Dbo2->column('timestamp without time zone'));
  265. $this->assertEquals('decimal', $this->Dbo2->column('decimal'));
  266. $this->assertEquals('decimal', $this->Dbo2->column('numeric'));
  267. $this->assertEquals('float', $this->Dbo2->column('float'));
  268. $this->assertEquals('float', $this->Dbo2->column('double precision'));
  269. $result = $this->Dbo2->column('bigint');
  270. $expected = 'biginteger';
  271. $this->assertEquals($expected, $result);
  272. }
  273. /**
  274. * testValueQuoting method
  275. *
  276. * @return void
  277. */
  278. public function testValueQuoting() {
  279. $this->assertEquals("1.200000", $this->Dbo->value(1.2, 'float'));
  280. $this->assertEquals("'1,2'", $this->Dbo->value('1,2', 'float'));
  281. $this->assertEquals("0", $this->Dbo->value('0', 'integer'));
  282. $this->assertEquals('NULL', $this->Dbo->value('', 'integer'));
  283. $this->assertEquals('NULL', $this->Dbo->value('', 'float'));
  284. $this->assertEquals("NULL", $this->Dbo->value('', 'integer', false));
  285. $this->assertEquals("NULL", $this->Dbo->value('', 'float', false));
  286. $this->assertEquals("'0.0'", $this->Dbo->value('0.0', 'float'));
  287. $this->assertEquals("'TRUE'", $this->Dbo->value('t', 'boolean'));
  288. $this->assertEquals("'FALSE'", $this->Dbo->value('f', 'boolean'));
  289. $this->assertEquals("'TRUE'", $this->Dbo->value(true));
  290. $this->assertEquals("'FALSE'", $this->Dbo->value(false));
  291. $this->assertEquals("'t'", $this->Dbo->value('t'));
  292. $this->assertEquals("'f'", $this->Dbo->value('f'));
  293. $this->assertEquals("'TRUE'", $this->Dbo->value('true', 'boolean'));
  294. $this->assertEquals("'FALSE'", $this->Dbo->value('false', 'boolean'));
  295. $this->assertEquals("'FALSE'", $this->Dbo->value('', 'boolean'));
  296. $this->assertEquals("'FALSE'", $this->Dbo->value(0, 'boolean'));
  297. $this->assertEquals("'TRUE'", $this->Dbo->value(1, 'boolean'));
  298. $this->assertEquals("'TRUE'", $this->Dbo->value('1', 'boolean'));
  299. $this->assertEquals("NULL", $this->Dbo->value(null, 'boolean'));
  300. $this->assertEquals("NULL", $this->Dbo->value(array()));
  301. }
  302. /**
  303. * test that localized floats don't cause trouble.
  304. *
  305. * @return void
  306. */
  307. public function testLocalizedFloats() {
  308. $restore = setlocale(LC_NUMERIC, 0);
  309. $this->skipIf(setlocale(LC_NUMERIC, 'de_DE') === false, "The German locale isn't available.");
  310. $result = $this->db->value(3.141593, 'float');
  311. $this->assertEquals("3.141593", $result);
  312. $result = $this->db->value(3.14);
  313. $this->assertEquals("3.140000", $result);
  314. setlocale(LC_NUMERIC, $restore);
  315. }
  316. /**
  317. * test that date and time columns do not generate errors with null and nullish values.
  318. *
  319. * @return void
  320. */
  321. public function testDateAndTimeAsNull() {
  322. $this->assertEquals('NULL', $this->Dbo->value(null, 'date'));
  323. $this->assertEquals('NULL', $this->Dbo->value('', 'date'));
  324. $this->assertEquals('NULL', $this->Dbo->value('', 'datetime'));
  325. $this->assertEquals('NULL', $this->Dbo->value(null, 'datetime'));
  326. $this->assertEquals('NULL', $this->Dbo->value('', 'timestamp'));
  327. $this->assertEquals('NULL', $this->Dbo->value(null, 'timestamp'));
  328. $this->assertEquals('NULL', $this->Dbo->value('', 'time'));
  329. $this->assertEquals('NULL', $this->Dbo->value(null, 'time'));
  330. }
  331. /**
  332. * Tests that different Postgres boolean 'flavors' are properly returned as native PHP booleans
  333. *
  334. * @return void
  335. */
  336. public function testBooleanNormalization() {
  337. $this->assertEquals(true, $this->Dbo2->boolean('t', false));
  338. $this->assertEquals(true, $this->Dbo2->boolean('true', false));
  339. $this->assertEquals(true, $this->Dbo2->boolean('TRUE', false));
  340. $this->assertEquals(true, $this->Dbo2->boolean(true, false));
  341. $this->assertEquals(true, $this->Dbo2->boolean(1, false));
  342. $this->assertEquals(true, $this->Dbo2->boolean(" ", false));
  343. $this->assertEquals(false, $this->Dbo2->boolean('f', false));
  344. $this->assertEquals(false, $this->Dbo2->boolean('false', false));
  345. $this->assertEquals(false, $this->Dbo2->boolean('FALSE', false));
  346. $this->assertEquals(false, $this->Dbo2->boolean(false, false));
  347. $this->assertEquals(false, $this->Dbo2->boolean(0, false));
  348. $this->assertEquals(false, $this->Dbo2->boolean('', false));
  349. }
  350. /**
  351. * test that default -> false in schemas works correctly.
  352. *
  353. * @return void
  354. */
  355. public function testBooleanDefaultFalseInSchema() {
  356. $this->loadFixtures('Datatype');
  357. $model = new Model(array('name' => 'Datatype', 'table' => 'datatypes', 'ds' => 'test'));
  358. $model->create();
  359. $this->assertSame(false, $model->data['Datatype']['bool']);
  360. }
  361. /**
  362. * testLastInsertIdMultipleInsert method
  363. *
  364. * @return void
  365. */
  366. public function testLastInsertIdMultipleInsert() {
  367. $this->loadFixtures('User');
  368. $db1 = ConnectionManager::getDataSource('test');
  369. $table = $db1->fullTableName('users', false);
  370. $password = '5f4dcc3b5aa765d61d8327deb882cf99';
  371. $db1->execute(
  372. "INSERT INTO {$table} (\"user\", password) VALUES ('mariano', '{$password}')"
  373. );
  374. $this->assertEquals(5, $db1->lastInsertId($table));
  375. $db1->execute("INSERT INTO {$table} (\"user\", password) VALUES ('hoge', '{$password}')");
  376. $this->assertEquals(6, $db1->lastInsertId($table));
  377. }
  378. /**
  379. * Tests that column types without default lengths in $columns do not have length values
  380. * applied when generating schemas.
  381. *
  382. * @return void
  383. */
  384. public function testColumnUseLength() {
  385. $result = array('name' => 'foo', 'type' => 'string', 'length' => 100, 'default' => 'FOO');
  386. $expected = '"foo" varchar(100) DEFAULT \'FOO\'';
  387. $this->assertEquals($expected, $this->Dbo->buildColumn($result));
  388. $result = array('name' => 'foo', 'type' => 'text', 'length' => 100, 'default' => 'FOO');
  389. $expected = '"foo" text DEFAULT \'FOO\'';
  390. $this->assertEquals($expected, $this->Dbo->buildColumn($result));
  391. }
  392. /**
  393. * Tests that binary data is escaped/unescaped properly on reads and writes
  394. *
  395. * @return void
  396. */
  397. public function testBinaryDataIntegrity() {
  398. $this->loadFixtures('BinaryTest');
  399. $data = '%PDF-1.3
  400. %ƒÂÚÂÎßÛ†–ƒ∆
  401. 4 0 obj
  402. << /Length 5 0 R /Filter /FlateDecode >>
  403. stream
  404. xµYMì€∆Ω„WÃ%)nï0¯îâ-«é]Q"πXµáÿ•Ip - P V,]Ú#c˚ˇ‰ut¥†∏Ti9 Ü=”›Ø_˜4>à∑‚Épcé¢Pxæ®2q\'
  405. 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
  406. ˛§¯ˇ:-˜ò7€ÓFæ∂∑Õ˛∆“V’>ılflëÅd«ÜQdI ›ÎB%W¿ΩıÉn~h vêCS>«é˛(ØôK!€¡zB!√
  407. [œÜ"ûß ·iH¸[Àºæ∑¯¡L,ÀÚAlS∫ˆ=∫Œ≤cÄr&ˆÈ:√ÿ£˚È«4fl•À]vc›bÅôÿî=siXe4/¡p]ã]ôÆIœ™ Ωflà_ƒ‚G?«7 ùÿ ı¯K4ïIpV◊÷·\'éµóªÚæ>î
  408. ;›sú!2fl¬F•/f∑j£
  409. dw"IÊÜπ<ôÿˆ%IG1ytÛDflXg|Éòa§˜}C˛¿ÿe°G´Ú±jÍm~¿/∂hã<#-¥•ıùe87€t˜õ6w}´{æ
  410. m‹ê– ∆¡ 6⁄\
  411. rAÀBùZ3aË‚r$G·$ó0Ñ üâUY4È™¡%C∑Ÿ2rc<Iõ-cï.
  412. [ŒöâFA†É‡+QglMÉîÉÄúÌ|¸»#x7¥«MgVÎ-GGÚ• I?Á‘”Lzw∞pHů◊nefqCî.nÕeè∆ÿÛy¡˙fb≤üŒHÜAëÕNq=´@ ’cQdÖúAÉIqñŸ˘+2&∏ Àù.gÅ‚ƒœ3EPƒOi—‰:>ÍCäı
  413. =Õec=ëR˝”eñ=<V$ì˙+x+¢ïÒÕ<àeWå»–˚∫Õ d§&£àf ]fPA´âtënöå∏◊ó „Ë@∆≠K´÷˘}a_CI˚©yòHg,ôSSVìBƒl4 L.ÈY…á,2∂íäÙ.$ó¸CäŸ*€óy
  414. π?G,_√·ÆÎç=^Vkvo±ó{§ƒ2»±¨Ïüo»ëD-ãé fió¥cVÙ\'™G~\'p¢%* ã˚÷
  415. ªºnh˚ºO^∏…®[Ó“‚ÅfıÌ≥∫F!Eœ(π∑T6`¬tΩÆ0ì»rTÎ`»Ñ«
  416. ]≈å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*¡·/';
  417. $model = new AppModel(array('name' => 'BinaryTest', 'ds' => 'test'));
  418. $model->save(compact('data'));
  419. $result = $model->find('first');
  420. $this->assertEquals($data, $result['BinaryTest']['data']);
  421. }
  422. /**
  423. * Tests passing PostgreSQL regular expression operators when building queries
  424. *
  425. * @return void
  426. */
  427. public function testRegexpOperatorConditionsParsing() {
  428. $this->assertSame(' WHERE "name" ~ \'[a-z_]+\'', $this->Dbo->conditions(array('name ~' => '[a-z_]+')));
  429. $this->assertSame(' WHERE "name" ~* \'[a-z_]+\'', $this->Dbo->conditions(array('name ~*' => '[a-z_]+')));
  430. $this->assertSame(' WHERE "name" !~ \'[a-z_]+\'', $this->Dbo->conditions(array('name !~' => '[a-z_]+')));
  431. $this->assertSame(' WHERE "name" !~* \'[a-z_]+\'', $this->Dbo->conditions(array('name !~*' => '[a-z_]+')));
  432. }
  433. /**
  434. * Tests the syntax of generated schema indexes
  435. *
  436. * @return void
  437. */
  438. public function testSchemaIndexSyntax() {
  439. $schema = new CakeSchema();
  440. $schema->tables = array('i18n' => array(
  441. 'id' => array(
  442. 'type' => 'integer', 'null' => false, 'default' => null,
  443. 'length' => 10, 'key' => 'primary'
  444. ),
  445. 'locale' => array('type' => 'string', 'null' => false, 'length' => 6, 'key' => 'index'),
  446. 'model' => array('type' => 'string', 'null' => false, 'key' => 'index'),
  447. 'foreign_key' => array(
  448. 'type' => 'integer', 'null' => false, 'length' => 10, 'key' => 'index'
  449. ),
  450. 'field' => array('type' => 'string', 'null' => false, 'key' => 'index'),
  451. 'content' => array('type' => 'text', 'null' => true, 'default' => null),
  452. 'indexes' => array(
  453. 'PRIMARY' => array('column' => 'id', 'unique' => 1),
  454. 'locale' => array('column' => 'locale', 'unique' => 0),
  455. 'model' => array('column' => 'model', 'unique' => 0),
  456. 'row_id' => array('column' => 'foreign_key', 'unique' => 0),
  457. 'field' => array('column' => 'field', 'unique' => 0)
  458. )
  459. ));
  460. $result = $this->Dbo->createSchema($schema);
  461. $this->assertNotRegExp('/^CREATE INDEX(.+);,$/', $result);
  462. }
  463. /**
  464. * testCakeSchema method
  465. *
  466. * Test that schema generated postgresql queries are valid. ref #5696
  467. * Check that the create statement for a schema generated table is the same as the original sql
  468. *
  469. * @return void
  470. */
  471. public function testCakeSchema() {
  472. $db1 = ConnectionManager::getDataSource('test');
  473. $db1->cacheSources = false;
  474. $db1->rawQuery('CREATE TABLE ' . $db1->fullTableName('datatype_tests') . ' (
  475. id serial NOT NULL,
  476. "varchar" character varying(40) NOT NULL,
  477. "full_length" character varying NOT NULL,
  478. "huge_int" bigint NOT NULL,
  479. "timestamp" timestamp without time zone,
  480. "date" date,
  481. CONSTRAINT test_data_types_pkey PRIMARY KEY (id)
  482. )');
  483. $schema = new CakeSchema(array('connection' => 'test'));
  484. $result = $schema->read(array(
  485. 'connection' => 'test',
  486. 'models' => array('DatatypeTest')
  487. ));
  488. $schema->tables = array(
  489. 'datatype_tests' => $result['tables']['missing']['datatype_tests']
  490. );
  491. $result = $db1->createSchema($schema, 'datatype_tests');
  492. $this->assertNotRegExp('/timestamp DEFAULT/', $result);
  493. $this->assertRegExp('/\"full_length\"\s*text\s.*,/', $result);
  494. $this->assertContains('timestamp ,', $result);
  495. $this->assertContains('"huge_int" bigint NOT NULL,', $result);
  496. $db1->query('DROP TABLE ' . $db1->fullTableName('datatype_tests'));
  497. $db1->query($result);
  498. $result2 = $schema->read(array(
  499. 'connection' => 'test',
  500. 'models' => array('DatatypeTest')
  501. ));
  502. $schema->tables = array('datatype_tests' => $result2['tables']['missing']['datatype_tests']);
  503. $result2 = $db1->createSchema($schema, 'datatype_tests');
  504. $this->assertEquals($result, $result2);
  505. $db1->query('DROP TABLE ' . $db1->fullTableName('datatype_tests'));
  506. }
  507. /**
  508. * testCakeSchemaBegserial method
  509. *
  510. * Test that schema generated postgresql queries are valid.
  511. *
  512. * @return void
  513. */
  514. public function testCakeSchemaBigserial() {
  515. $db1 = ConnectionManager::getDataSource('test');
  516. $db1->cacheSources = false;
  517. $db1->rawQuery('CREATE TABLE ' . $db1->fullTableName('bigserial_tests') . ' (
  518. "id" bigserial NOT NULL,
  519. "varchar" character varying(40) NOT NULL,
  520. PRIMARY KEY ("id")
  521. )');
  522. $schema = new CakeSchema(array('connection' => 'test'));
  523. $result = $schema->read(array(
  524. 'connection' => 'test',
  525. 'models' => array('BigserialTest')
  526. ));
  527. $schema->tables = array(
  528. 'bigserial_tests' => $result['tables']['missing']['bigserial_tests']
  529. );
  530. $result = $db1->createSchema($schema, 'bigserial_tests');
  531. $this->assertContains('"id" bigserial NOT NULL,', $result);
  532. $db1->query('DROP TABLE ' . $db1->fullTableName('bigserial_tests'));
  533. }
  534. /**
  535. * Test index generation from table info.
  536. *
  537. * @return void
  538. */
  539. public function testIndexGeneration() {
  540. $name = $this->Dbo->fullTableName('index_test', false, false);
  541. $this->Dbo->query('CREATE TABLE ' . $name . ' ("id" serial NOT NULL PRIMARY KEY, "bool" integer, "small_char" varchar(50), "description" varchar(40) )');
  542. $this->Dbo->query('CREATE INDEX pointless_bool ON ' . $name . '("bool")');
  543. $this->Dbo->query('CREATE UNIQUE INDEX char_index ON ' . $name . '("small_char")');
  544. $expected = array(
  545. 'PRIMARY' => array('unique' => true, 'column' => 'id'),
  546. 'pointless_bool' => array('unique' => false, 'column' => 'bool'),
  547. 'char_index' => array('unique' => true, 'column' => 'small_char'),
  548. );
  549. $result = $this->Dbo->index($name);
  550. $this->Dbo->query('DROP TABLE ' . $name);
  551. $this->assertEquals($expected, $result);
  552. $name = $this->Dbo->fullTableName('index_test_2', false, false);
  553. $this->Dbo->query('CREATE TABLE ' . $name . ' ("id" serial NOT NULL PRIMARY KEY, "bool" integer, "small_char" varchar(50), "description" varchar(40) )');
  554. $this->Dbo->query('CREATE UNIQUE INDEX multi_col ON ' . $name . '("small_char", "bool")');
  555. $expected = array(
  556. 'PRIMARY' => array('unique' => true, 'column' => 'id'),
  557. 'multi_col' => array('unique' => true, 'column' => array('small_char', 'bool')),
  558. );
  559. $result = $this->Dbo->index($name);
  560. $this->Dbo->query('DROP TABLE ' . $name);
  561. $this->assertEquals($expected, $result);
  562. }
  563. /**
  564. * Test the alterSchema capabilities of postgres
  565. *
  566. * @return void
  567. */
  568. public function testAlterSchema() {
  569. $Old = new CakeSchema(array(
  570. 'connection' => 'test',
  571. 'name' => 'AlterPosts',
  572. 'alter_posts' => array(
  573. 'id' => array('type' => 'integer', 'key' => 'primary'),
  574. 'author_id' => array('type' => 'integer', 'null' => false),
  575. 'title' => array('type' => 'string', 'null' => true),
  576. 'body' => array('type' => 'text'),
  577. 'published' => array('type' => 'string', 'length' => 1, 'default' => 'N'),
  578. 'created' => array('type' => 'datetime'),
  579. 'updated' => array('type' => 'datetime'),
  580. )
  581. ));
  582. $this->Dbo->query($this->Dbo->createSchema($Old));
  583. $New = new CakeSchema(array(
  584. 'connection' => 'test',
  585. 'name' => 'AlterPosts',
  586. 'alter_posts' => array(
  587. 'id' => array('type' => 'integer', 'key' => 'primary'),
  588. 'author_id' => array('type' => 'integer', 'null' => true),
  589. 'title' => array('type' => 'string', 'null' => false, 'default' => 'my title'),
  590. 'body' => array('type' => 'string', 'length' => 500),
  591. 'status' => array('type' => 'integer', 'length' => 3, 'default' => 1),
  592. 'created' => array('type' => 'datetime'),
  593. 'updated' => array('type' => 'datetime'),
  594. )
  595. ));
  596. $this->Dbo->query($this->Dbo->alterSchema($New->compare($Old), 'alter_posts'));
  597. $model = new CakeTestModel(array('table' => 'alter_posts', 'ds' => 'test'));
  598. $result = $model->schema();
  599. $this->assertTrue(isset($result['status']));
  600. $this->assertFalse(isset($result['published']));
  601. $this->assertEquals('string', $result['body']['type']);
  602. $this->assertEquals(1, $result['status']['default']);
  603. $this->assertEquals(true, $result['author_id']['null']);
  604. $this->assertEquals(false, $result['title']['null']);
  605. $this->Dbo->query($this->Dbo->dropSchema($New));
  606. $New = new CakeSchema(array(
  607. 'connection' => 'test_suite',
  608. 'name' => 'AlterPosts',
  609. 'alter_posts' => array(
  610. 'id' => array('type' => 'string', 'length' => 36, 'key' => 'primary'),
  611. 'author_id' => array('type' => 'integer', 'null' => false),
  612. 'title' => array('type' => 'string', 'null' => true),
  613. 'body' => array('type' => 'text'),
  614. 'published' => array('type' => 'string', 'length' => 1, 'default' => 'N'),
  615. 'created' => array('type' => 'datetime'),
  616. 'updated' => array('type' => 'datetime'),
  617. )
  618. ));
  619. $result = $this->Dbo->alterSchema($New->compare($Old), 'alter_posts');
  620. $this->assertNotRegExp('/varchar\(36\) NOT NULL/i', $result);
  621. }
  622. /**
  623. * Test the alterSchema changing boolean to integer
  624. *
  625. * @return void
  626. */
  627. public function testAlterSchemaBooleanToIntegerField() {
  628. $default = array(
  629. 'connection' => 'test',
  630. 'name' => 'BoolField',
  631. 'bool_fields' => array(
  632. 'id' => array('type' => 'integer', 'key' => 'primary'),
  633. 'name' => array('type' => 'string', 'length' => 50),
  634. 'active' => array('type' => 'boolean', 'null' => false),
  635. )
  636. );
  637. $Old = new CakeSchema($default);
  638. $result = $this->Dbo->query($this->Dbo->createSchema($Old));
  639. $this->assertTrue($result);
  640. $modified = $default;
  641. $modified['bool_fields']['active'] = array('type' => 'integer', 'null' => true);
  642. $New = new CakeSchema($modified);
  643. $query = $this->Dbo->alterSchema($New->compare($Old));
  644. $result = $this->Dbo->query($query);
  645. $this->Dbo->query($this->Dbo->dropSchema($Old));
  646. }
  647. /**
  648. * Test the alter index capabilities of postgres
  649. *
  650. * @return void
  651. */
  652. public function testAlterIndexes() {
  653. $this->Dbo->cacheSources = false;
  654. $schema1 = new CakeSchema(array(
  655. 'name' => 'AlterTest1',
  656. 'connection' => 'test',
  657. 'altertest' => array(
  658. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  659. 'name' => array('type' => 'string', 'null' => false, 'length' => 50),
  660. 'group1' => array('type' => 'integer', 'null' => true),
  661. 'group2' => array('type' => 'integer', 'null' => true)
  662. )
  663. ));
  664. $this->Dbo->rawQuery($this->Dbo->createSchema($schema1));
  665. $schema2 = new CakeSchema(array(
  666. 'name' => 'AlterTest2',
  667. 'connection' => 'test',
  668. 'altertest' => array(
  669. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  670. 'name' => array('type' => 'string', 'null' => false, 'length' => 50),
  671. 'group1' => array('type' => 'integer', 'null' => true),
  672. 'group2' => array('type' => 'integer', 'null' => true),
  673. 'indexes' => array(
  674. 'name_idx' => array('unique' => false, 'column' => 'name'),
  675. 'group_idx' => array('unique' => false, 'column' => 'group1'),
  676. 'compound_idx' => array('unique' => false, 'column' => array('group1', 'group2')),
  677. 'PRIMARY' => array('unique' => true, 'column' => 'id')
  678. )
  679. )
  680. ));
  681. $this->Dbo->query($this->Dbo->alterSchema($schema2->compare($schema1)));
  682. $indexes = $this->Dbo->index('altertest');
  683. $this->assertEquals($schema2->tables['altertest']['indexes'], $indexes);
  684. // Change three indexes, delete one and add another one
  685. $schema3 = new CakeSchema(array(
  686. 'name' => 'AlterTest3',
  687. 'connection' => 'test',
  688. 'altertest' => array(
  689. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  690. 'name' => array('type' => 'string', 'null' => false, 'length' => 50),
  691. 'group1' => array('type' => 'integer', 'null' => true),
  692. 'group2' => array('type' => 'integer', 'null' => true),
  693. 'indexes' => array(
  694. 'name_idx' => array('unique' => true, 'column' => 'name'),
  695. 'group_idx' => array('unique' => false, 'column' => 'group2'),
  696. 'compound_idx' => array('unique' => false, 'column' => array('group2', 'group1')),
  697. 'another_idx' => array('unique' => false, 'column' => array('group1', 'name')))
  698. )));
  699. $this->Dbo->query($this->Dbo->alterSchema($schema3->compare($schema2)));
  700. $indexes = $this->Dbo->index('altertest');
  701. $this->assertEquals($schema3->tables['altertest']['indexes'], $indexes);
  702. // Compare us to ourself.
  703. $this->assertEquals(array(), $schema3->compare($schema3));
  704. // Drop the indexes
  705. $this->Dbo->query($this->Dbo->alterSchema($schema1->compare($schema3)));
  706. $indexes = $this->Dbo->index('altertest');
  707. $this->assertEquals(array(), $indexes);
  708. $this->Dbo->query($this->Dbo->dropSchema($schema1));
  709. }
  710. /**
  711. * Test the alterSchema RENAME statements
  712. *
  713. * @return void
  714. */
  715. public function testAlterSchemaRenameTo() {
  716. $query = $this->Dbo->alterSchema(array(
  717. 'posts' => array(
  718. 'change' => array(
  719. 'title' => array('name' => 'subject', 'type' => 'string', 'null' => false)
  720. )
  721. )
  722. ));
  723. $this->assertContains('RENAME "title" TO "subject";', $query);
  724. $this->assertContains('ALTER COLUMN "subject" TYPE', $query);
  725. $this->assertNotContains(";\n\tALTER COLUMN \"subject\" TYPE", $query);
  726. $this->assertNotContains('ALTER COLUMN "title" TYPE "subject"', $query);
  727. }
  728. /**
  729. * Test it is possible to use virtual field with postgresql
  730. *
  731. * @return void
  732. */
  733. public function testVirtualFields() {
  734. $this->loadFixtures('Article', 'Comment', 'User', 'Attachment', 'Tag', 'ArticlesTag');
  735. $Article = new Article;
  736. $Article->virtualFields = array(
  737. 'next_id' => 'Article.id + 1',
  738. 'complex' => 'Article.title || Article.body',
  739. 'functional' => 'COALESCE(User.user, Article.title)',
  740. 'subquery' => 'SELECT count(*) FROM ' . $Article->Comment->table
  741. );
  742. $result = $Article->find('first');
  743. $this->assertEquals(2, $result['Article']['next_id']);
  744. $this->assertEquals($result['Article']['complex'], $result['Article']['title'] . $result['Article']['body']);
  745. $this->assertEquals($result['Article']['functional'], $result['User']['user']);
  746. $this->assertEquals(6, $result['Article']['subquery']);
  747. }
  748. /**
  749. * Test that virtual fields work with SQL constants
  750. *
  751. * @return void
  752. */
  753. public function testVirtualFieldAsAConstant() {
  754. $this->loadFixtures('Article', 'Comment');
  755. $Article = ClassRegistry::init('Article');
  756. $Article->virtualFields = array(
  757. 'empty' => "NULL",
  758. 'number' => 43,
  759. 'truth' => 'TRUE'
  760. );
  761. $result = $Article->find('first');
  762. $this->assertNull($result['Article']['empty']);
  763. $this->assertTrue($result['Article']['truth']);
  764. $this->assertEquals(43, $result['Article']['number']);
  765. }
  766. /**
  767. * Tests additional order options for postgres
  768. *
  769. * @return void
  770. */
  771. public function testOrderAdditionalParams() {
  772. $result = $this->Dbo->order(array('title' => 'DESC NULLS FIRST', 'body' => 'DESC'));
  773. $expected = ' ORDER BY "title" DESC NULLS FIRST, "body" DESC';
  774. $this->assertEquals($expected, $result);
  775. }
  776. /**
  777. * Test it is possible to do a SELECT COUNT(DISTINCT Model.field)
  778. * query in postgres and it gets correctly quoted
  779. *
  780. * @return void
  781. */
  782. public function testQuoteDistinctInFunction() {
  783. $this->loadFixtures('Article');
  784. $Article = new Article;
  785. $result = $this->Dbo->fields($Article, null, array('COUNT(DISTINCT Article.id)'));
  786. $expected = array('COUNT(DISTINCT "Article"."id")');
  787. $this->assertEquals($expected, $result);
  788. $result = $this->Dbo->fields($Article, null, array('COUNT(DISTINCT id)'));
  789. $expected = array('COUNT(DISTINCT "id")');
  790. $this->assertEquals($expected, $result);
  791. $result = $this->Dbo->fields($Article, null, array('COUNT(DISTINCT FUNC(id))'));
  792. $expected = array('COUNT(DISTINCT FUNC("id"))');
  793. $this->assertEquals($expected, $result);
  794. }
  795. /**
  796. * test that saveAll works even with conditions that lack a model name.
  797. *
  798. * @return void
  799. */
  800. public function testUpdateAllWithNonQualifiedConditions() {
  801. $this->loadFixtures('Article');
  802. $Article = new Article();
  803. $result = $Article->updateAll(array('title' => "'Awesome'"), array('title' => 'Third Article'));
  804. $this->assertTrue($result);
  805. $result = $Article->find('count', array(
  806. 'conditions' => array('Article.title' => 'Awesome')
  807. ));
  808. $this->assertEquals(1, $result, 'Article count is wrong or fixture has changed.');
  809. }
  810. /**
  811. * test alterSchema on two tables.
  812. *
  813. * @return void
  814. */
  815. public function testAlteringTwoTables() {
  816. $schema1 = new CakeSchema(array(
  817. 'name' => 'AlterTest1',
  818. 'connection' => 'test',
  819. 'altertest' => array(
  820. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  821. 'name' => array('type' => 'string', 'null' => false, 'length' => 50),
  822. ),
  823. 'other_table' => array(
  824. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  825. 'name' => array('type' => 'string', 'null' => false, 'length' => 50),
  826. )
  827. ));
  828. $schema2 = new CakeSchema(array(
  829. 'name' => 'AlterTest1',
  830. 'connection' => 'test',
  831. 'altertest' => array(
  832. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  833. 'field_two' => array('type' => 'string', 'null' => false, 'length' => 50),
  834. ),
  835. 'other_table' => array(
  836. 'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
  837. 'field_two' => array('type' => 'string', 'null' => false, 'length' => 50),
  838. )
  839. ));
  840. $result = $this->db->alterSchema($schema2->compare($schema1));
  841. $this->assertEquals(2, substr_count($result, 'field_two'), 'Too many fields');
  842. $this->assertFalse(strpos(';ALTER', $result), 'Too many semi colons');
  843. }
  844. /**
  845. * test encoding setting.
  846. *
  847. * @return void
  848. */
  849. public function testEncoding() {
  850. $result = $this->Dbo->setEncoding('UTF8');
  851. $this->assertTrue($result);
  852. $result = $this->Dbo->getEncoding();
  853. $this->assertEquals('UTF8', $result);
  854. $result = $this->Dbo->setEncoding('EUC_JP'); /* 'EUC_JP' is right character code name in PostgreSQL */
  855. $this->assertTrue($result);
  856. $result = $this->Dbo->getEncoding();
  857. $this->assertEquals('EUC_JP', $result);
  858. }
  859. /**
  860. * Test truncate with a mock.
  861. *
  862. * @return void
  863. */
  864. public function testTruncateStatements() {
  865. $this->loadFixtures('Article', 'User');
  866. $db = ConnectionManager::getDatasource('test');
  867. $schema = $db->config['schema'];
  868. $Article = new Article();
  869. $this->Dbo = $this->getMock('Postgres', array('execute'), array($db->config));
  870. $this->Dbo->expects($this->at(0))->method('execute')
  871. ->with("DELETE FROM \"$schema\".\"articles\"");
  872. $this->Dbo->truncate($Article);
  873. $this->Dbo->expects($this->at(0))->method('execute')
  874. ->with("DELETE FROM \"$schema\".\"articles\"");
  875. $this->Dbo->truncate('articles');
  876. // #2355: prevent duplicate prefix
  877. $this->Dbo->config['prefix'] = 'tbl_';
  878. $Article->tablePrefix = 'tbl_';
  879. $this->Dbo->expects($this->at(0))->method('execute')
  880. ->with("DELETE FROM \"$schema\".\"tbl_articles\"");
  881. $this->Dbo->truncate($Article);
  882. $this->Dbo->expects($this->at(0))->method('execute')
  883. ->with("DELETE FROM \"$schema\".\"tbl_articles\"");
  884. $this->Dbo->truncate('articles');
  885. }
  886. /**
  887. * Test nested transaction
  888. *
  889. * @return void
  890. */
  891. public function testNestedTransaction() {
  892. $this->Dbo->useNestedTransactions = true;
  893. $this->skipIf($this->Dbo->nestedTransactionSupported() === false, 'The Postgres server do not support nested transaction');
  894. $this->loadFixtures('Article');
  895. $model = new Article();
  896. $model->hasOne = $model->hasMany = $model->belongsTo = $model->hasAndBelongsToMany = array();
  897. $model->cacheQueries = false;
  898. $this->Dbo->cacheMethods = false;
  899. $this->assertTrue($this->Dbo->begin());
  900. $this->assertNotEmpty($model->read(null, 1));
  901. $this->assertTrue($this->Dbo->begin());
  902. $this->assertTrue($model->delete(1));
  903. $this->assertEmpty($model->read(null, 1));
  904. $this->assertTrue($this->Dbo->rollback());
  905. $this->assertNotEmpty($model->read(null, 1));
  906. $this->assertTrue($this->Dbo->begin());
  907. $this->assertTrue($model->delete(1));
  908. $this->assertEmpty($model->read(null, 1));
  909. $this->assertTrue($this->Dbo->commit());
  910. $this->assertEmpty($model->read(null, 1));
  911. $this->assertTrue($this->Dbo->rollback());
  912. $this->assertNotEmpty($model->read(null, 1));
  913. }
  914. public function testResetSequence() {
  915. $model = new Article();
  916. $table = $this->Dbo->fullTableName($model, false);
  917. $fields = array(
  918. 'id', 'user_id', 'title', 'body', 'published',
  919. );
  920. $values = array(
  921. array(1, 1, 'test', 'first post', false),
  922. array(2, 1, 'test 2', 'second post post', false),
  923. );
  924. $this->Dbo->insertMulti($table, $fields, $values);
  925. $sequence = $this->Dbo->getSequence($table);
  926. $result = $this->Dbo->rawQuery("SELECT nextval('$sequence')");
  927. $original = $result->fetch(PDO::FETCH_ASSOC);
  928. $this->assertTrue($this->Dbo->resetSequence($table, 'id'));
  929. $result = $this->Dbo->rawQuery("SELECT currval('$sequence')");
  930. $new = $result->fetch(PDO::FETCH_ASSOC);
  931. $this->assertTrue($new['currval'] > $original['nextval'], 'Sequence did not update');
  932. }
  933. public function testSettings() {
  934. Configure::write('Cache.disable', true);
  935. $this->Dbo = ConnectionManager::getDataSource('test');
  936. $this->skipIf(!($this->Dbo instanceof Postgres));
  937. $config2 = $this->Dbo->config;
  938. $config2['settings']['datestyle'] = 'sql, dmy';
  939. ConnectionManager::create('test2', $config2);
  940. $dbo2 = new Postgres($config2, true);
  941. $expected = array(array('r' => date('d/m/Y')));
  942. $r = $dbo2->fetchRow('SELECT now()::date AS "r"');
  943. $this->assertEquals($expected, $r);
  944. $dbo2->execute('SET DATESTYLE TO ISO');
  945. $dbo2->disconnect();
  946. }
  947. /**
  948. * Test the limit function.
  949. *
  950. * @return void
  951. */
  952. public function testLimit() {
  953. $db = $this->Dbo;
  954. $result = $db->limit('0');
  955. $this->assertNull($result);
  956. $result = $db->limit('10');
  957. $this->assertEquals(' LIMIT 10', $result);
  958. $result = $db->limit('FARTS', 'BOOGERS');
  959. $this->assertEquals(' LIMIT 0 OFFSET 0', $result);
  960. $result = $db->limit(20, 10);
  961. $this->assertEquals(' LIMIT 20 OFFSET 10', $result);
  962. $result = $db->limit(10, 300000000000000000000000000000);
  963. $scientificNotation = sprintf('%.1E', 300000000000000000000000000000);
  964. $this->assertNotContains($scientificNotation, $result);
  965. }
  966. }