Skip to content

Commit bf2b0ee

Browse files
authored
Merge pull request #35 from dmstr/feature/postgre-file-migration
added "FileMigration" for postgre
2 parents 7d10ff8 + b175c82 commit bf2b0ee

File tree

2 files changed

+89
-0
lines changed

2 files changed

+89
-0
lines changed

db/postgre/FileMigration.php

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
<?php
2+
/**
3+
* @link http://www.diemeisterei.de/
4+
* @copyright Copyright (c) 2025 diemeisterei GmbH, Stuttgart
5+
*
6+
* For the full copyright and license information, please view the LICENSE
7+
* file that was distributed with this source code.
8+
*/
9+
10+
namespace dmstr\db\postgre;
11+
12+
use Exception;
13+
use yii\db\Migration;
14+
15+
/**
16+
* Class FileMigration
17+
* @package common\components
18+
* Elias Luhr <[email protected]>
19+
*/
20+
class FileMigration extends Migration
21+
{
22+
public $file = null;
23+
24+
public function init()
25+
{
26+
parent::init();
27+
28+
if ($this->file === null) {
29+
$reflection = new \ReflectionClass($this);
30+
$this->file = str_replace('.php', '.sql', $reflection->getFileName());
31+
} else {
32+
$reflection = new \ReflectionClass($this);
33+
$this->file = dirname($reflection->getFileName()).DIRECTORY_SEPARATOR.$this->file;
34+
}
35+
36+
if (!is_file($this->file)) {
37+
throw new Exception("File {$this->file} not found");
38+
}
39+
}
40+
41+
/**
42+
* {@inheritdoc}
43+
*/
44+
public function up()
45+
{
46+
// Open connection if not opened already as we execute raw SQL on PDO we have no "autoconnect magick" here.
47+
if (!$this->db->isActive) {
48+
$this->db->open();
49+
}
50+
51+
$sql = file_get_contents($this->file);
52+
53+
try {
54+
$result = $this->db->pdo->exec($sql);
55+
echo "Success exec: " . $this->file . "\n";
56+
} catch (Exception $exception) {
57+
echo "\n-----\n" . $exception->getMessage() . "\n-----\n";
58+
return false;
59+
}
60+
61+
return true;
62+
}
63+
64+
/**
65+
* {@inheritdoc}
66+
*/
67+
public function down()
68+
{
69+
echo $this::class . " cannot be reverted.\n";
70+
return false;
71+
}
72+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
<?php
2+
/**
3+
* This view is used by console/controllers/MigrateController.php
4+
* The following variables are available in this view:
5+
*/
6+
/* @var $className string the new migration class name */
7+
8+
echo "<?php\n";
9+
?>
10+
11+
use dmstr\db\postgre\FileMigration;
12+
13+
class <?= $className ?> extends FileMigration
14+
{
15+
# create a sql file `<?= $className ?>.sql` or adjust and uncomment the following line, do not change this class name
16+
//public $file = 'custom-filename.sql';
17+
}

0 commit comments

Comments
 (0)