Completed
Push — master ( 84dee3...084275 )
by Michal
36:03
created

PostgresAdapterTest::testDropIndexByName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 22
Code Lines 17

Duplication

Lines 22
Ratio 100 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 22
loc 22
rs 9.2
c 1
b 0
f 0
cc 1
eloc 17
nc 1
nop 0
1
<?php
2
3
namespace Test\Phinx\Db\Adapter;
4
5
use Symfony\Component\Console\Output\NullOutput;
6
use Phinx\Db\Adapter\PostgresAdapter;
7
8
class PostgresAdapterTest extends \PHPUnit_Framework_TestCase
9
{
10
    /**
11
     * Check if Postgres is enabled in the current PHP
12
     *
13
     * @return boolean
14
     */
15
    private static function isPostgresAvailable()
16
    {
17
        static $available;
18
19
        if (is_null($available)) {
20
            $available = in_array('pgsql', \PDO::getAvailableDrivers());
21
        }
22
23
        return $available;
24
    }
25
26
    /**
27
     * @var \Phinx\Db\Adapter\PostgresqlAdapter
28
     */
29
    private $adapter;
30
31
    public function setUp()
32
    {
33
        if (!TESTS_PHINX_DB_ADAPTER_POSTGRES_ENABLED) {
34
            $this->markTestSkipped('Postgres tests disabled.  See TESTS_PHINX_DB_ADAPTER_POSTGRES_ENABLED constant.');
35
        }
36
37
        if (!self::isPostgresAvailable()) {
38
            $this->markTestSkipped('Postgres is not available.  Please install php-pdo-pgsql or equivalent package.');
39
        }
40
41
        $options = array(
42
            'host' => TESTS_PHINX_DB_ADAPTER_POSTGRES_HOST,
43
            'name' => TESTS_PHINX_DB_ADAPTER_POSTGRES_DATABASE,
44
            'user' => TESTS_PHINX_DB_ADAPTER_POSTGRES_USERNAME,
45
            'pass' => TESTS_PHINX_DB_ADAPTER_POSTGRES_PASSWORD,
46
            'port' => TESTS_PHINX_DB_ADAPTER_POSTGRES_PORT,
47
            'schema' => TESTS_PHINX_DB_ADAPTER_POSTGRES_DATABASE_SCHEMA
48
        );
49
        $this->adapter = new PostgresAdapter($options, new NullOutput());
0 ignored issues
show
Documentation Bug introduced by
It seems like new \Phinx\Db\Adapter\Po...le\Output\NullOutput()) of type object<Phinx\Db\Adapter\PostgresAdapter> is incompatible with the declared type object<Phinx\Db\Adapter\PostgresqlAdapter> of property $adapter.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
50
51
        $this->adapter->dropAllSchemas();
52
        $this->adapter->createSchema($options['schema']);
53
54
        // leave the adapter in a disconnected state for each test
55
        $this->adapter->disconnect();
56
    }
57
58
    public function tearDown()
59
    {
60
        if ($this->adapter) {
61
            $this->adapter->dropAllSchemas();
62
            unset($this->adapter);
63
        }
64
    }
65
66
    public function testConnection()
67
    {
68
        $this->assertTrue($this->adapter->getConnection() instanceof \PDO);
69
    }
70
71 View Code Duplication
    public function testConnectionWithoutPort()
72
    {
73
        $options = $this->adapter->getOptions();
74
        unset($options['port']);
75
        $this->adapter->setOptions($options);
76
        $this->assertTrue($this->adapter->getConnection() instanceof \PDO);
77
    }
78
79 View Code Duplication
    public function testConnectionWithInvalidCredentials()
80
    {
81
        $options = array(
82
            'host' => TESTS_PHINX_DB_ADAPTER_POSTGRES_HOST,
83
            'name' => TESTS_PHINX_DB_ADAPTER_POSTGRES_DATABASE,
84
            'port' => TESTS_PHINX_DB_ADAPTER_POSTGRES_PORT,
85
            'user' => 'invaliduser',
86
            'pass' => 'invalidpass'
87
        );
88
89
        try {
90
            $adapter = new PostgresAdapter($options, new NullOutput());
91
            $adapter->connect();
92
            $this->fail('Expected the adapter to throw an exception');
93
        } catch (\InvalidArgumentException $e) {
94
            $this->assertInstanceOf(
95
                'InvalidArgumentException',
96
                $e,
97
                'Expected exception of type InvalidArgumentException, got ' . get_class($e)
98
            );
99
            $this->assertRegExp('/There was a problem connecting to the database/', $e->getMessage());
100
        }
101
    }
102
103 View Code Duplication
    public function testCreatingTheSchemaTableOnConnect()
104
    {
105
        $this->adapter->connect();
106
        $this->assertTrue($this->adapter->hasTable($this->adapter->getSchemaTableName()));
107
        $this->adapter->dropTable($this->adapter->getSchemaTableName());
108
        $this->assertFalse($this->adapter->hasTable($this->adapter->getSchemaTableName()));
109
        $this->adapter->disconnect();
110
        $this->adapter->connect();
111
        $this->assertTrue($this->adapter->hasTable($this->adapter->getSchemaTableName()));
112
    }
113
114
    public function testSchemaTableIsCreatedWithPrimaryKey()
115
    {
116
        $this->adapter->connect();
117
        $table = new \Phinx\Db\Table($this->adapter->getSchemaTableName(), array(), $this->adapter);
0 ignored issues
show
Unused Code introduced by
$table is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
118
        $this->assertTrue($this->adapter->hasIndex($this->adapter->getSchemaTableName(), array('version')));
119
    }
120
121
    public function testQuoteSchemaName()
122
    {
123
        $this->assertEquals('"schema"', $this->adapter->quoteSchemaName('schema'));
124
        $this->assertEquals('"schema.schema"', $this->adapter->quoteSchemaName('schema.schema'));
125
    }
126
127
    public function testQuoteTableName()
128
    {
129
        $this->assertEquals('"public"."table"', $this->adapter->quoteTableName('table'));
130
        $this->assertEquals('"public"."table.table"', $this->adapter->quoteTableName('table.table'));
131
    }
132
133
    public function testQuoteColumnName()
134
    {
135
        $this->assertEquals('"string"', $this->adapter->quoteColumnName('string'));
136
        $this->assertEquals('"string.string"', $this->adapter->quoteColumnName('string.string'));
137
    }
138
139 View Code Duplication
    public function testCreateTable()
140
    {
141
        $table = new \Phinx\Db\Table('ntable', array(), $this->adapter);
142
        $table->addColumn('realname', 'string')
143
              ->addColumn('email', 'integer')
144
              ->save();
145
        $this->assertTrue($this->adapter->hasTable('ntable'));
146
        $this->assertTrue($this->adapter->hasColumn('ntable', 'id'));
147
        $this->assertTrue($this->adapter->hasColumn('ntable', 'realname'));
148
        $this->assertTrue($this->adapter->hasColumn('ntable', 'email'));
149
        $this->assertFalse($this->adapter->hasColumn('ntable', 'address'));
150
    }
151
152 View Code Duplication
    public function testCreateTableCustomIdColumn()
153
    {
154
        $table = new \Phinx\Db\Table('ntable', array('id' => 'custom_id'), $this->adapter);
155
        $table->addColumn('realname', 'string')
156
              ->addColumn('email', 'integer')
157
              ->save();
158
        $this->assertTrue($this->adapter->hasTable('ntable'));
159
        $this->assertTrue($this->adapter->hasColumn('ntable', 'custom_id'));
160
        $this->assertTrue($this->adapter->hasColumn('ntable', 'realname'));
161
        $this->assertTrue($this->adapter->hasColumn('ntable', 'email'));
162
        $this->assertFalse($this->adapter->hasColumn('ntable', 'address'));
163
    }
164
165 View Code Duplication
    public function testCreateTableWithNoPrimaryKey()
166
    {
167
        $options = array(
168
            'id' => false
169
        );
170
        $table = new \Phinx\Db\Table('atable', $options, $this->adapter);
171
        $table->addColumn('user_id', 'integer')
172
              ->save();
173
        $this->assertFalse($this->adapter->hasColumn('atable', 'id'));
174
    }
175
176 View Code Duplication
    public function testCreateTableWithMultiplePrimaryKeys()
177
    {
178
        $options = array(
179
            'id'            => false,
180
            'primary_key'   => array('user_id', 'tag_id')
181
        );
182
        $table = new \Phinx\Db\Table('table1', $options, $this->adapter);
183
        $table->addColumn('user_id', 'integer')
184
              ->addColumn('tag_id', 'integer')
185
              ->save();
186
        $this->assertTrue($this->adapter->hasIndex('table1', array('user_id', 'tag_id')));
187
        $this->assertTrue($this->adapter->hasIndex('table1', array('tag_id', 'USER_ID')));
188
        $this->assertFalse($this->adapter->hasIndex('table1', array('tag_id', 'user_email')));
189
    }
190
191 View Code Duplication
    public function testCreateTableWithMultipleIndexes()
192
    {
193
        $table = new \Phinx\Db\Table('table1', array(), $this->adapter);
194
        $table->addColumn('email', 'string')
195
              ->addColumn('name', 'string')
196
              ->addIndex('email')
197
              ->addIndex('name')
198
              ->save();
199
        $this->assertTrue($this->adapter->hasIndex('table1', array('email')));
200
        $this->assertTrue($this->adapter->hasIndex('table1', array('name')));
201
        $this->assertFalse($this->adapter->hasIndex('table1', array('email', 'user_email')));
202
        $this->assertFalse($this->adapter->hasIndex('table1', array('email', 'user_name')));
203
    }
204
205 View Code Duplication
    public function testCreateTableWithUniqueIndexes()
206
    {
207
        $table = new \Phinx\Db\Table('table1', array(), $this->adapter);
208
        $table->addColumn('email', 'string')
209
              ->addIndex('email', array('unique' => true))
210
              ->save();
211
        $this->assertTrue($this->adapter->hasIndex('table1', array('email')));
212
        $this->assertFalse($this->adapter->hasIndex('table1', array('email', 'user_email')));
213
    }
214
215 View Code Duplication
    public function testCreateTableWithNamedIndexes()
216
    {
217
        $table = new \Phinx\Db\Table('table1', array(), $this->adapter);
218
        $table->addColumn('email', 'string')
219
              ->addIndex('email', array('name' => 'myemailindex'))
220
              ->save();
221
        $this->assertTrue($this->adapter->hasIndex('table1', array('email')));
222
        $this->assertFalse($this->adapter->hasIndex('table1', array('email', 'user_email')));
223
        $this->assertTrue($this->adapter->hasIndexByName('table1', 'myemailindex'));
224
    }
225
226 View Code Duplication
    public function testRenameTable()
227
    {
228
        $table = new \Phinx\Db\Table('table1', array(), $this->adapter);
229
        $table->save();
230
        $this->assertTrue($this->adapter->hasTable('table1'));
231
        $this->assertFalse($this->adapter->hasTable('table2'));
232
        $this->adapter->renameTable('table1', 'table2');
233
        $this->assertFalse($this->adapter->hasTable('table1'));
234
        $this->assertTrue($this->adapter->hasTable('table2'));
235
    }
236
237 View Code Duplication
    public function testAddColumn()
238
    {
239
        $table = new \Phinx\Db\Table('table1', array(), $this->adapter);
240
        $table->save();
241
        $this->assertFalse($table->hasColumn('email'));
242
        $table->addColumn('email', 'string')
243
              ->save();
244
        $this->assertTrue($table->hasColumn('email'));
245
    }
246
247 View Code Duplication
    public function testAddColumnWithDefaultValue()
248
    {
249
        $table = new \Phinx\Db\Table('table1', array(), $this->adapter);
250
        $table->save();
251
        $table->addColumn('default_zero', 'string', array('default' => 'test'))
252
              ->save();
253
        $columns = $this->adapter->getColumns('table1');
254
        foreach ($columns as $column) {
255
            if ($column->getName() == 'default_zero') {
256
                $this->assertEquals("'test'::character varying", $column->getDefault());
257
            }
258
        }
259
    }
260
261 View Code Duplication
    public function testAddColumnWithDefaultZero()
262
    {
263
        $table = new \Phinx\Db\Table('table1', array(), $this->adapter);
264
        $table->save();
265
        $table->addColumn('default_zero', 'integer', array('default' => 0))
266
              ->save();
267
        $columns = $this->adapter->getColumns('table1');
268
        foreach ($columns as $column) {
269
            if ($column->getName() == 'default_zero') {
270
                $this->assertNotNull($column->getDefault());
271
                $this->assertEquals('0', $column->getDefault());
272
            }
273
        }
274
    }
275
276
    public function testAddColumnWithDefaultBoolean()
277
    {
278
        $table = new \Phinx\Db\Table('table1', array(), $this->adapter);
279
        $table->save();
280
        $table->addColumn('default_true', 'boolean', array('default' => true))
281
              ->addColumn('default_false', 'boolean', array('default' => false))
282
              ->save();
283
        $columns = $this->adapter->getColumns('table1');
284
        foreach ($columns as $column) {
285
            if ($column->getName() == 'default_true') {
286
                $this->assertNotNull($column->getDefault());
287
                $this->assertEquals('true', $column->getDefault());
288
            }
289
            if ($column->getName() == 'default_false') {
290
                $this->assertNotNull($column->getDefault());
291
                $this->assertEquals('false', $column->getDefault());
292
            }
293
        }
294
    }
295
296
    public function testAddDecimalWithPrecisionAndScale()
297
    {
298
        $table = new \Phinx\Db\Table('table1', array(), $this->adapter);
299
        $table->save();
300
        $table->addColumn('number', 'decimal', array('precision' => 10, 'scale' => 2))
301
            ->addColumn('number2', 'decimal', array('limit' => 12))
302
            ->addColumn('number3', 'decimal')
303
            ->save();
304
        $columns = $this->adapter->getColumns('table1');
305
        foreach ($columns as $column) {
306
            if ($column->getName() == 'number') {
307
                $this->assertEquals("10", $column->getPrecision());
308
                $this->assertEquals("2", $column->getScale());
309
            }
310
311
            if ($column->getName() == 'number2') {
312
                $this->assertEquals("12", $column->getPrecision());
313
                $this->assertEquals("0", $column->getScale());
314
            }
315
        }
316
    }
317
318
    public function providerArrayType()
319
    {
320
        return array(
321
            array('array_text', 'text[]'),
322
            array('array_char', 'char[]'),
323
            array('array_integer', 'integer[]'),
324
            array('array_float', 'float[]'),
325
            array('array_decimal', 'decimal[]'),
326
            array('array_timestamp', 'timestamp[]'),
327
            array('array_time', 'time[]'),
328
            array('array_date', 'date[]'),
329
            array('array_boolean', 'boolean[]'),
330
            array('array_json', 'json[]'),
331
            array('array_json2d', 'json[][]'),
332
            array('array_json3d', 'json[][][]'),
333
            array('array_uuid', 'uuid[]'),
334
        );
335
    }
336
337
    /**
338
     * @dataProvider providerArrayType
339
     */
340
    public function testAddColumnArrayType($column_name, $column_type)
341
    {
342
        $table = new \Phinx\Db\Table('table1', array(), $this->adapter);
343
        $table->save();
344
        $this->assertFalse($table->hasColumn($column_name));
345
        $table->addColumn($column_name, $column_type)
346
            ->save();
347
        $this->assertTrue($table->hasColumn($column_name));
348
    }
349
350 View Code Duplication
    public function testRenameColumn()
351
    {
352
        $table = new \Phinx\Db\Table('t', array(), $this->adapter);
353
        $table->addColumn('column1', 'string')
354
              ->save();
355
        $this->assertTrue($this->adapter->hasColumn('t', 'column1'));
356
        $this->assertFalse($this->adapter->hasColumn('t', 'column2'));
357
        $this->adapter->renameColumn('t', 'column1', 'column2');
358
        $this->assertFalse($this->adapter->hasColumn('t', 'column1'));
359
        $this->assertTrue($this->adapter->hasColumn('t', 'column2'));
360
    }
361
362 View Code Duplication
    public function testRenamingANonExistentColumn()
363
    {
364
        $table = new \Phinx\Db\Table('t', array(), $this->adapter);
365
        $table->addColumn('column1', 'string')
366
              ->save();
367
368
        try {
369
            $this->adapter->renameColumn('t', 'column2', 'column1');
370
            $this->fail('Expected the adapter to throw an exception');
371
        } catch (\InvalidArgumentException $e) {
372
            $this->assertInstanceOf(
373
                'InvalidArgumentException',
374
                $e,
375
                'Expected exception of type InvalidArgumentException, got ' . get_class($e)
376
            );
377
            $this->assertEquals('The specified column does not exist: column2', $e->getMessage());
378
        }
379
    }
380
381 View Code Duplication
    public function testChangeColumn()
382
    {
383
        $table = new \Phinx\Db\Table('t', array(), $this->adapter);
384
        $table->addColumn('column1', 'string')
385
              ->save();
386
        $this->assertTrue($this->adapter->hasColumn('t', 'column1'));
387
        $newColumn1 = new \Phinx\Db\Table\Column();
388
        $newColumn1->setType('string');
389
        $table->changeColumn('column1', $newColumn1);
390
        $this->assertTrue($this->adapter->hasColumn('t', 'column1'));
391
        $newColumn2 = new \Phinx\Db\Table\Column();
392
        $newColumn2->setName('column2')
393
                   ->setType('string')
394
                   ->setNull(true);
395
        $table->changeColumn('column1', $newColumn2);
396
        $this->assertFalse($this->adapter->hasColumn('t', 'column1'));
397
        $this->assertTrue($this->adapter->hasColumn('t', 'column2'));
398
        $columns = $this->adapter->getColumns('t');
399
        foreach ($columns as $column) {
400
            if ($column->getName() == 'column2') {
401
                $this->assertTrue($column->isNull());
402
            }
403
        }
404
    }
405
406
    public function testChangeColumnWithDefault() {
407
        $table = new \Phinx\Db\Table('t', array(), $this->adapter);
408
        $table->addColumn('column1', 'string')
409
              ->save();
410
411
        $newColumn1 = new \Phinx\Db\Table\Column();
412
        $newColumn1->setName('column1')
413
                   ->setType('string')
414
                   ->setNull(true);
415
416
        $newColumn1->setDefault('Test');
417
        $table->changeColumn('column1', $newColumn1);
418
419
        $columns = $this->adapter->getColumns('t');
420
        foreach ($columns as $column) {
421
            if ($column->getName() === 'column1') {
422
                $this->assertTrue($column->isNull());
423
                $this->assertRegExp('/Test/', $column->getDefault());
424
            }
425
        }
426
    }
427
428
    public function testChangeColumnWithDropDefault() {
429
        $table = new \Phinx\Db\Table('t', array(), $this->adapter);
430
        $table->addColumn('column1', 'string', array('default' => 'Test'))
431
              ->save();
432
433
        $columns = $this->adapter->getColumns('t');
434
        foreach ($columns as $column) {
435
            if ($column->getName() === 'column1') {
436
                $this->assertRegExp('/Test/', $column->getDefault());
437
            }
438
        }
439
440
        $newColumn1 = new \Phinx\Db\Table\Column();
441
        $newColumn1->setName('column1')
442
                   ->setType('string');
443
444
        $table->changeColumn('column1', $newColumn1);
445
446
        $columns = $this->adapter->getColumns('t');
447
        foreach ($columns as $column) {
448
            if ($column->getName() === 'column1') {
449
                $this->assertNull($column->getDefault());
450
            }
451
        }
452
    }
453
454 View Code Duplication
    public function testDropColumn()
455
    {
456
        $table = new \Phinx\Db\Table('t', array(), $this->adapter);
457
        $table->addColumn('column1', 'string')
458
              ->save();
459
        $this->assertTrue($this->adapter->hasColumn('t', 'column1'));
460
        $this->adapter->dropColumn('t', 'column1');
461
        $this->assertFalse($this->adapter->hasColumn('t', 'column1'));
462
    }
463
464 View Code Duplication
    public function testGetColumns()
465
    {
466
        $table = new \Phinx\Db\Table('t', array(), $this->adapter);
467
        $table->addColumn('column1', 'string')
468
              ->addColumn('column2', 'integer', array('limit' => PostgresAdapter::INT_SMALL))
469
              ->addColumn('column3', 'integer')
470
              ->addColumn('column4', 'biginteger')
471
              ->addColumn('column5', 'text')
472
              ->addColumn('column6', 'float')
473
              ->addColumn('column7', 'decimal')
474
              ->addColumn('column8', 'time')
475
              ->addColumn('column9', 'timestamp')
476
              ->addColumn('column10', 'date')
477
              ->addColumn('column11', 'boolean')
478
              ->addColumn('column12', 'datetime')
479
              ->addColumn('column13', 'binary')
480
              ->addColumn('column14', 'string', array('limit' => 10));
481
        $pendingColumns = $table->getPendingColumns();
482
        $table->save();
483
        $columns = $this->adapter->getColumns('t');
484
        $this->assertCount(count($pendingColumns) + 1, $columns);
485
        for ($i = 0; $i++; $i < count($pendingColumns)) {
486
            $this->assertEquals($pendingColumns[$i], $columns[$i+1]);
487
        }
488
    }
489
490 View Code Duplication
    public function testAddIndex()
491
    {
492
        $table = new \Phinx\Db\Table('table1', array(), $this->adapter);
493
        $table->addColumn('email', 'string')
494
              ->save();
495
        $this->assertFalse($table->hasIndex('email'));
496
        $table->addIndex('email')
497
              ->save();
498
        $this->assertTrue($table->hasIndex('email'));
499
    }
500
501 View Code Duplication
    public function testDropIndex()
502
    {
503
         // single column index
504
        $table = new \Phinx\Db\Table('table1', array(), $this->adapter);
505
        $table->addColumn('email', 'string')
506
              ->addIndex('email')
507
              ->save();
508
        $this->assertTrue($table->hasIndex('email'));
509
        $this->adapter->dropIndex($table->getName(), 'email');
510
        $this->assertFalse($table->hasIndex('email'));
511
512
        // multiple column index
513
        $table2 = new \Phinx\Db\Table('table2', array(), $this->adapter);
514
        $table2->addColumn('fname', 'string')
515
               ->addColumn('lname', 'string')
516
               ->addIndex(array('fname', 'lname'))
517
               ->save();
518
        $this->assertTrue($table2->hasIndex(array('fname', 'lname')));
519
        $this->adapter->dropIndex($table2->getName(), array('fname', 'lname'));
520
        $this->assertFalse($table2->hasIndex(array('fname', 'lname')));
521
522
        // index with name specified, but dropping it by column name
523
        $table3 = new \Phinx\Db\Table('table3', array(), $this->adapter);
524
        $table3->addColumn('email', 'string')
525
              ->addIndex('email', array('name' => 'someindexname'))
526
              ->save();
527
        $this->assertTrue($table3->hasIndex('email'));
528
        $this->adapter->dropIndex($table3->getName(), 'email');
529
        $this->assertFalse($table3->hasIndex('email'));
530
531
        // multiple column index with name specified
532
        $table4 = new \Phinx\Db\Table('table4', array(), $this->adapter);
533
        $table4->addColumn('fname', 'string')
534
               ->addColumn('lname', 'string')
535
               ->addIndex(array('fname', 'lname'), array('name' => 'multiname'))
536
               ->save();
537
        $this->assertTrue($table4->hasIndex(array('fname', 'lname')));
538
        $this->adapter->dropIndex($table4->getName(), array('fname', 'lname'));
539
        $this->assertFalse($table4->hasIndex(array('fname', 'lname')));
540
    }
541
542 View Code Duplication
    public function testDropIndexByName()
543
    {
544
        // single column index
545
        $table = new \Phinx\Db\Table('table1', array(), $this->adapter);
546
        $table->addColumn('email', 'string')
547
              ->addIndex('email', array('name' => 'myemailindex'))
548
              ->save();
549
        $this->assertTrue($table->hasIndex('email'));
550
        $this->adapter->dropIndexByName($table->getName(), 'myemailindex');
551
        $this->assertFalse($table->hasIndex('email'));
552
553
        // multiple column index
554
        $table2 = new \Phinx\Db\Table('table2', array(), $this->adapter);
555
        $table2->addColumn('fname', 'string')
556
               ->addColumn('lname', 'string')
557
               ->addIndex(array('fname', 'lname'),
558
                          array('name' => 'twocolumnuniqueindex', 'unique' => true))
559
               ->save();
560
        $this->assertTrue($table2->hasIndex(array('fname', 'lname')));
561
        $this->adapter->dropIndexByName($table2->getName(), 'twocolumnuniqueindex');
562
        $this->assertFalse($table2->hasIndex(array('fname', 'lname')));
563
    }
564
565
    public function testAddForeignKey()
566
    {
567
        $refTable = new \Phinx\Db\Table('ref_table', array(), $this->adapter);
568
        $refTable->addColumn('field1', 'string')->save();
569
570
        $table = new \Phinx\Db\Table('table', array(), $this->adapter);
571
        $table->addColumn('ref_table_id', 'integer')->save();
572
573
        $fk = new \Phinx\Db\Table\ForeignKey();
574
        $fk->setReferencedTable($refTable)
575
           ->setColumns(array('ref_table_id'))
576
           ->setReferencedColumns(array('id'));
577
578
        $this->adapter->addForeignKey($table, $fk);
579
        $this->assertTrue($this->adapter->hasForeignKey($table->getName(), array('ref_table_id')));
580
    }
581
582 View Code Duplication
    public function testDropForeignKey()
583
    {
584
        $refTable = new \Phinx\Db\Table('ref_table', array(), $this->adapter);
585
        $refTable->addColumn('field1', 'string')->save();
586
587
        $table = new \Phinx\Db\Table('table', array(), $this->adapter);
588
        $table->addColumn('ref_table_id', 'integer')->save();
589
590
        $fk = new \Phinx\Db\Table\ForeignKey();
591
        $fk->setReferencedTable($refTable)
592
           ->setColumns(array('ref_table_id'))
593
           ->setReferencedColumns(array('id'));
594
595
        $this->adapter->addForeignKey($table, $fk);
596
        $this->assertTrue($this->adapter->hasForeignKey($table->getName(), array('ref_table_id')));
597
        $this->adapter->dropForeignKey($table->getName(), array('ref_table_id'));
598
        $this->assertFalse($this->adapter->hasForeignKey($table->getName(), array('ref_table_id')));
599
    }
600
601
    public function testHasDatabase()
602
    {
603
        $this->assertFalse($this->adapter->hasDatabase('fake_database_name'));
604
        $this->assertTrue($this->adapter->hasDatabase(TESTS_PHINX_DB_ADAPTER_POSTGRES_DATABASE));
605
    }
606
607 View Code Duplication
    public function testDropDatabase()
608
    {
609
        $this->assertFalse($this->adapter->hasDatabase('phinx_temp_database'));
610
        $this->adapter->createDatabase('phinx_temp_database');
611
        $this->assertTrue($this->adapter->hasDatabase('phinx_temp_database'));
612
        $this->adapter->dropDatabase('phinx_temp_database');
613
    }
614
615
    public function testCreateSchema()
616
    {
617
        $this->adapter->createSchema('foo');
618
        $this->assertTrue($this->adapter->hasSchema('foo'));
619
    }
620
621
    public function testDropSchema()
622
    {
623
        $this->adapter->createSchema('foo');
624
        $this->assertTrue($this->adapter->hasSchema('foo'));
625
        $this->adapter->dropSchema('foo');
626
        $this->assertFalse($this->adapter->hasSchema('foo'));
627
    }
628
629
    public function testDropAllSchemas()
630
    {
631
        $this->adapter->createSchema('foo');
632
        $this->adapter->createSchema('bar');
633
634
        $this->assertTrue($this->adapter->hasSchema('foo'));
635
        $this->assertTrue($this->adapter->hasSchema('bar'));
636
        $this->adapter->dropAllSchemas();
637
        $this->assertFalse($this->adapter->hasSchema('foo'));
638
        $this->assertFalse($this->adapter->hasSchema('bar'));
639
    }
640
641
    /**
642
     * @expectedException \RuntimeException
643
     * @expectedExceptionMessage The type: "idontexist" is not supported
644
     */
645
    public function testInvalidSqlType()
646
    {
647
        $this->adapter->getSqlType('idontexist');
648
    }
649
650
    public function testGetPhinxType()
651
    {
652
        $this->assertEquals('integer', $this->adapter->getPhinxType('int'));
653
        $this->assertEquals('integer', $this->adapter->getPhinxType('int4'));
654
        $this->assertEquals('integer', $this->adapter->getPhinxType('integer'));
655
656
        $this->assertEquals('biginteger', $this->adapter->getPhinxType('bigint'));
657
        $this->assertEquals('biginteger', $this->adapter->getPhinxType('int8'));
658
659
        $this->assertEquals('decimal', $this->adapter->getPhinxType('decimal'));
660
        $this->assertEquals('decimal', $this->adapter->getPhinxType('numeric'));
661
662
        $this->assertEquals('float', $this->adapter->getPhinxType('real'));
663
        $this->assertEquals('float', $this->adapter->getPhinxType('float4'));
664
665
        $this->assertEquals('boolean', $this->adapter->getPhinxType('bool'));
666
        $this->assertEquals('boolean', $this->adapter->getPhinxType('boolean'));
667
668
        $this->assertEquals('string', $this->adapter->getPhinxType('character varying'));
669
        $this->assertEquals('string', $this->adapter->getPhinxType('varchar'));
670
671
        $this->assertEquals('text', $this->adapter->getPhinxType('text'));
672
673
        $this->assertEquals('time', $this->adapter->getPhinxType('time'));
674
        $this->assertEquals('time', $this->adapter->getPhinxType('timetz'));
675
        $this->assertEquals('time', $this->adapter->getPhinxType('time with time zone'));
676
        $this->assertEquals('time', $this->adapter->getPhinxType('time without time zone'));
677
678
        $this->assertEquals('datetime', $this->adapter->getPhinxType('timestamp'));
679
        $this->assertEquals('datetime', $this->adapter->getPhinxType('timestamptz'));
680
        $this->assertEquals('datetime', $this->adapter->getPhinxType('timestamp with time zone'));
681
        $this->assertEquals('datetime', $this->adapter->getPhinxType('timestamp without time zone'));
682
683
        $this->assertEquals('uuid', $this->adapter->getPhinxType('uuid'));
684
685
    }
686
687 View Code Duplication
    public function testCanAddColumnComment()
688
    {
689
        $table = new \Phinx\Db\Table('table1', array(), $this->adapter);
690
        $table->addColumn('field1', 'string', array('comment' => $comment = 'Comments from column "field1"'))
691
              ->save();
692
693
        $row = $this->adapter->fetchRow(
694
            'SELECT
695
                (select pg_catalog.col_description(oid,cols.ordinal_position::int)
696
            from pg_catalog.pg_class c
697
            where c.relname=cols.table_name ) as column_comment
698
            FROM information_schema.columns cols
699
            WHERE cols.table_catalog=\''. TESTS_PHINX_DB_ADAPTER_POSTGRES_DATABASE .'\'
700
            AND cols.table_name=\'table1\'
701
            AND cols.column_name = \'field1\''
702
        );
703
704
        $this->assertEquals($comment, $row['column_comment'], 'Dont set column comment correctly');
705
    }
706
707
    /**
708
     * @depends testCanAddColumnComment
709
     */
710 View Code Duplication
    public function testCanChangeColumnComment()
711
    {
712
        $table = new \Phinx\Db\Table('table1', array(), $this->adapter);
713
        $table->addColumn('field1', 'string', array('comment' => 'Comments from column "field1"'))
714
              ->save();
715
716
        $table->changeColumn('field1', 'string', array('comment' => $comment = 'New Comments from column "field1"'))
717
              ->save();
718
719
        $row = $this->adapter->fetchRow(
720
            'SELECT
721
                (select pg_catalog.col_description(oid,cols.ordinal_position::int)
722
            from pg_catalog.pg_class c
723
            where c.relname=cols.table_name ) as column_comment
724
            FROM information_schema.columns cols
725
            WHERE cols.table_catalog=\''. TESTS_PHINX_DB_ADAPTER_POSTGRES_DATABASE .'\'
726
            AND cols.table_name=\'table1\'
727
            AND cols.column_name = \'field1\''
728
        );
729
730
        $this->assertEquals($comment, $row['column_comment'], 'Dont change column comment correctly');
731
    }
732
733
    /**
734
     * @depends testCanAddColumnComment
735
     */
736 View Code Duplication
    public function testCanRemoveColumnComment()
737
    {
738
        $table = new \Phinx\Db\Table('table1', array(), $this->adapter);
739
        $table->addColumn('field1', 'string', array('comment' => 'Comments from column "field1"'))
740
              ->save();
741
742
        $table->changeColumn('field1', 'string', array('comment' => 'null'))
743
              ->save();
744
745
        $row = $this->adapter->fetchRow(
746
            'SELECT
747
                (select pg_catalog.col_description(oid,cols.ordinal_position::int)
748
            from pg_catalog.pg_class c
749
            where c.relname=cols.table_name ) as column_comment
750
            FROM information_schema.columns cols
751
            WHERE cols.table_catalog=\''. TESTS_PHINX_DB_ADAPTER_POSTGRES_DATABASE .'\'
752
            AND cols.table_name=\'table1\'
753
            AND cols.column_name = \'field1\''
754
        );
755
756
        $this->assertEmpty($row['column_comment'], 'Dont remove column comment correctly');
757
    }
758
759
    /**
760
     * @depends testCanAddColumnComment
761
     */
762
    public function testCanAddMultipleCommentsToOneTable()
763
    {
764
        $table = new \Phinx\Db\Table('table1', array(), $this->adapter);
765
        $table->addColumn('comment1', 'string', array(
766
            'comment' => $comment1 = 'first comment'
767
            ))
768
            ->addColumn('comment2', 'string', array(
769
            'comment' => $comment2 = 'second comment'
770
            ))
771
            ->save();
772
773
        $row = $this->adapter->fetchRow(
774
            'SELECT
775
                (select pg_catalog.col_description(oid,cols.ordinal_position::int)
776
            from pg_catalog.pg_class c
777
            where c.relname=cols.table_name ) as column_comment
778
            FROM information_schema.columns cols
779
            WHERE cols.table_catalog=\''. TESTS_PHINX_DB_ADAPTER_POSTGRES_DATABASE .'\'
780
            AND cols.table_name=\'table1\'
781
            AND cols.column_name = \'comment1\''
782
        );
783
784
        $this->assertEquals($comment1, $row['column_comment'], 'Could not create first column comment');
785
786
        $row = $this->adapter->fetchRow(
787
            'SELECT
788
                (select pg_catalog.col_description(oid,cols.ordinal_position::int)
789
            from pg_catalog.pg_class c
790
            where c.relname=cols.table_name ) as column_comment
791
            FROM information_schema.columns cols
792
            WHERE cols.table_catalog=\''. TESTS_PHINX_DB_ADAPTER_POSTGRES_DATABASE .'\'
793
            AND cols.table_name=\'table1\'
794
            AND cols.column_name = \'comment2\''
795
        );
796
797
        $this->assertEquals($comment2, $row['column_comment'], 'Could not create second column comment');
798
    }
799
800
    /**
801
     * @depends testCanAddColumnComment
802
     */
803 View Code Duplication
    public function testColumnsAreResetBetweenTables()
804
    {
805
        $table = new \Phinx\Db\Table('widgets', array(), $this->adapter);
806
        $table->addColumn('transport', 'string', array(
807
            'comment' => $comment = 'One of: car, boat, truck, plane, train'
808
            ))
809
            ->save();
810
811
        $table = new \Phinx\Db\Table('things', array(), $this->adapter);
812
        $table->addColumn('speed', 'integer')
813
            ->save();
814
815
        $row = $this->adapter->fetchRow(
816
            'SELECT
817
                (select pg_catalog.col_description(oid,cols.ordinal_position::int)
818
            from pg_catalog.pg_class c
819
            where c.relname=cols.table_name ) as column_comment
820
            FROM information_schema.columns cols
821
            WHERE cols.table_catalog=\''. TESTS_PHINX_DB_ADAPTER_POSTGRES_DATABASE .'\'
822
            AND cols.table_name=\'widgets\'
823
            AND cols.column_name = \'transport\''
824
        );
825
826
        $this->assertEquals($comment, $row['column_comment'], 'Could not create column comment');
827
    }
828
829
    /**
830
     * Test that column names are properly escaped when creating Foreign Keys
831
     */
832 View Code Duplication
    public function testForignKeysArePropertlyEscaped()
833
    {
834
        $userId = 'user';
835
        $sessionId = 'session';
836
837
        $local = new \Phinx\Db\Table('users', array('primary_key' => $userId, 'id' => $userId), $this->adapter);
838
        $local->create();
839
840
        $foreign = new \Phinx\Db\Table('sessions', array('primary_key' => $sessionId, 'id' => $sessionId), $this->adapter);
841
        $foreign->addColumn('user', 'integer')
842
                ->addForeignKey('user', 'users', $userId)
843
                ->create();
844
845
        $this->assertTrue($foreign->hasForeignKey('user'));
846
    }
847
848
    public function testTimestampWithTimezone()
849
    {
850
        $table = new \Phinx\Db\Table('tztable', array('id' => false), $this->adapter);
851
        $table
852
            ->addColumn('timestamp_tz', 'timestamp', array('timezone' => true))
853
            ->addColumn('time_tz', 'time', array('timezone' => true))
854
            ->addColumn('date_notz', 'date', array('timezone' => true)) /* date columns cannot have timestamp */
855
            ->addColumn('time_notz', 'timestamp') /* default for timezone option is false */
856
            ->save();
857
858
        $this->assertTrue($this->adapter->hasColumn('tztable', 'timestamp_tz'));
859
        $this->assertTrue($this->adapter->hasColumn('tztable', 'time_tz'));
860
        $this->assertTrue($this->adapter->hasColumn('tztable', 'date_notz'));
861
        $this->assertTrue($this->adapter->hasColumn('tztable', 'time_notz'));
862
863
        $columns = $this->adapter->getColumns('tztable');
864
        foreach ($columns as $column) {
865
            if (substr($column->getName(), -4) === 'notz') {
866
                $this->assertFalse($column->isTimezone(), 'column: ' . $column->getName());
867
            } else {
868
                $this->assertTrue($column->isTimezone(), 'column: ' . $column->getName());
869
            }
870
        }
871
    }
872
873
    public function testInsertData()
874
    {
875
        $table = new \Phinx\Db\Table('table1', array(), $this->adapter);
876
        $table->addColumn('column1', 'string')
877
              ->addColumn('column2', 'integer')
878
              ->insert(array(
879
                  array(
880
                      'column1' => 'value1',
881
                      'column2' => 1
882
                  ),
883
                  array(
884
                      'column1' => 'value2',
885
                      'column2' => 2
886
                  )
887
              ))
888
              ->save();
889
890
        $rows = $this->adapter->fetchAll('SELECT * FROM table1');
891
        $this->assertEquals('value1', $rows[0]['column1']);
892
        $this->assertEquals('value2', $rows[1]['column1']);
893
        $this->assertEquals(1, $rows[0]['column2']);
894
        $this->assertEquals(2, $rows[1]['column2']);
895
    }
896
}
897