Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
n/a
0 / 0
n/a
0 / 0
CRAP
n/a
0 / 0
Db
n/a
0 / 0
n/a
0 / 0
22
n/a
0 / 0
 startExecuteSqlFile
n/a
0 / 0
n/a
0 / 0
8
 executeSql
n/a
0 / 0
n/a
0 / 0
1
 startUsingDatabase
n/a
0 / 0
n/a
0 / 0
4
 startTestDataImport
n/a
0 / 0
n/a
0 / 0
1
 startConfigDataImport
n/a
0 / 0
n/a
0 / 0
1
 startMigrations
n/a
0 / 0
n/a
0 / 0
5
 executeTestData
n/a
0 / 0
n/a
0 / 0
2
1<?php
2
3namespace BO\Zmsdb\Cli;
4
5/**
6 * @codeCoverageIgnore
7 * @SuppressWarnings(Short)
8 */
9class Db
10{
11    public static $baseDSN = '';
12
13    public static function startExecuteSqlFile($file, $dbname = null, $verbose = true)
14    {
15        $pdo = self::startUsingDatabase($dbname, $verbose);
16        $startTime = microtime(true);
17
18        // Check if file is compressed or not
19        $isCompressed = (substr($file, -3) === '.gz');
20
21        if ($isCompressed) {
22            $sqlFile = gzopen($file, 'r');
23            $readFunction = 'gzgets';
24            $closeFunction = 'gzclose';
25        } else {
26            $sqlFile = fopen($file, 'r');
27            $readFunction = 'fgets';
28            $closeFunction = 'fclose';
29        }
30
31        if ($verbose) {
32            \App::$log->info('Importing SQL file', ['file' => basename($file)]);
33        }
34        $query = '';
35        while ($line = $readFunction($sqlFile)) {
36            $query .= $line;
37            if (preg_match('/;\s*$/', $line)) {
38                try {
39                    $pdo->exec($query);
40                    //echo "Successful:\n$query\n";
41                    $query = '';
42                } catch (\Exception $exception) {
43                    if ($verbose) {
44                        \App::$log->error('SQL import failed', [
45                            'file' => basename($file),
46                            'method' => __METHOD__,
47                            'exception' => get_class($exception),
48                            'message' => $exception->getMessage(),
49                            'code' => $exception->getCode(),
50                        ]);
51                    }
52                    throw $exception;
53                }
54            }
55        }
56        $closeFunction($sqlFile);
57        $time = round(microtime(true) - $startTime, 3);
58        if ($verbose) {
59            \App::$log->info('SQL import finished', [
60                'file' => basename($file),
61                'seconds' => $time,
62            ]);
63        }
64    }
65
66    public static function executeSql($query, $dbname = null)
67    {
68        $pdo = self::startUsingDatabase($dbname, false);
69        $pdo->exec($query);
70    }
71
72    public static function startUsingDatabase($dbname = null, $verbose = true): \BO\Zmsdb\Connection\Pdo
73    {
74        if (!self::$baseDSN) {
75            self::$baseDSN = \BO\Zmsdb\Connection\Select::$writeSourceName;
76        }
77        \BO\Zmsdb\Connection\Select::closeWriteConnection();
78        if ($dbname === null) {
79            \BO\Zmsdb\Connection\Select::$writeSourceName = self::$baseDSN;
80        } else {
81            $dbname_zms =& \BO\Zmsdb\Connection\Select::$dbname_zms;
82            \BO\Zmsdb\Connection\Select::$writeSourceName =
83                preg_replace("#dbname=$dbname_zms.*?;#", "dbname=$dbname;", self::$baseDSN);
84        }
85
86        if ($verbose) {
87            \App::$log->info('Using database connection', [
88                'dsn' => \BO\Zmsdb\Connection\Select::$writeSourceName,
89            ]);
90        }
91
92        $pdo = \BO\Zmsdb\Connection\Select::getWriteConnection();
93        return $pdo;
94    }
95
96    public static function startTestDataImport($fixtures, $filename = 'mysql_zmsbo.sql')
97    {
98        $dbname_zms =& \BO\Zmsdb\Connection\Select::$dbname_zms;
99
100        $pdo = self::startUsingDatabase('information_schema');
101        $pdo->exec("DROP DATABASE IF EXISTS `$dbname_zms`;");
102        $pdo->exec("CREATE DATABASE IF NOT EXISTS `$dbname_zms`;");
103
104        self::startExecuteSqlFile($fixtures . '/' . $filename);
105    }
106
107    public static function startConfigDataImport()
108    {
109        $defaults = new \BO\Zmsentities\Config();
110        (new \BO\Zmsdb\Config())->updateEntity($defaults);
111    }
112
113    public static function startMigrations($migrationList, $commit = true)
114    {
115        if (!is_array($migrationList)) {
116            $migrationList = glob($migrationList . '/*.sql');
117        }
118        sort($migrationList);
119        $pdo = self::startUsingDatabase();
120        $migrationsDoneList = $pdo->fetchPairs('SELECT filename, changeTimestamp FROM migrations');
121        $addedMigrations = 0;
122        foreach ($migrationList as $migrationFile) {
123            $migrationName = basename($migrationFile);
124            if (!array_key_exists($migrationName, $migrationsDoneList)) {
125                $addedMigrations++;
126                if (!$commit) {
127                    \App::$log->info('Pending migration', [
128                        'index' => $addedMigrations,
129                        'migration' => $migrationName,
130                    ]);
131                } else {
132                    self::startExecuteSqlFile($migrationFile);
133                    $pdo->prepare('INSERT INTO `migrations` SET `filename` = :filename')
134                        ->execute(['filename' => $migrationName]);
135                }
136            }
137        }
138        \App::$log->info('Migration check finished', [
139            'completed' => count($migrationsDoneList),
140            'added' => $addedMigrations,
141        ]);
142        return $addedMigrations;
143    }
144
145    public static function executeTestData(string $testName, string $step)
146    {
147        $fixtures = realpath(__DIR__ . '/../../../tests/Zmsdb/fixtures/');
148        $sqlFile = $fixtures . '/' . $testName . '/' . $step . '.sql';
149
150        if (! file_exists($sqlFile)) {
151            return;
152        }
153
154        self::startExecuteSqlFile(
155            $sqlFile,
156            null,
157            false
158        );
159    }
160}