Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

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