Skip to content

Commit 697ab81

Browse files
author
Fredrick Peter
committed
Migration and DB Import Upgrades
1 parent b64429f commit 697ab81

File tree

2 files changed

+34
-4
lines changed

2 files changed

+34
-4
lines changed

README.md

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -554,7 +554,7 @@ AutoloadEnv::configurePagination([
554554
]);
555555
```
556556

557-
- or Helpers Function
557+
- or -- `Helpers Function`
558558
```
559559
configure_pagination([
560560
'allow' => true,
@@ -1215,8 +1215,6 @@ $db->repair('tb_wallet');
12151215
| $db->getConnection() | get_connection() |
12161216

12171217
## Database Import
1218-
<details><summary>Read more...</summary>
1219-
12201218
- You can use this class to import .sql into a database programatically
12211219

12221220
```
@@ -1232,7 +1230,12 @@ $response = $import->DatabaseImport('orm.sql');
12321230
->response == 400 (Query to database error
12331231
->response == 200 (Success importing to database
12341232
```
1235-
</details>
1233+
1234+
- or -- `Helpers Function`
1235+
1236+
```
1237+
import()->DatabaseImport('orm.sql');
1238+
```
12361239

12371240
## Update Env Variable
12381241
- You can use this class to import .sql into a database programatically

src/DBImport.php

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,33 @@ public function DatabaseImport($path_to_sql = NULL)
6161
// get content
6262
$sql = file_get_contents($this->realpath);
6363

64+
// Replace Creation of tables
65+
$sql = str_replace("CREATE TABLE", "CREATE TABLE IF NOT EXISTS", $sql);
66+
67+
// Replace Insert into
68+
$sql = str_replace("INSERT INTO", "INSERT IGNORE INTO", $sql);
69+
70+
// Replace Creation of triggers
71+
$sql = str_replace("CREATE TRIGGER", "CREATE TRIGGER IF NOT EXISTS", $sql);
72+
73+
// Replace delimiter
74+
$sql = str_replace(['DELIMITER', '$$'], "", $sql);
75+
76+
// Check if table exists and remove ALTER TABLE queries
77+
$matches = [];
78+
preg_match_all('/ALTER TABLE `(\w+)`/i', $sql, $matches);
79+
$tableNames = $matches[1];
80+
81+
// loop through to check if table exist already and ignore ALTER queries
82+
foreach ($tableNames as $tableName) {
83+
$tableExistsQuery = "SHOW TABLES LIKE '{$tableName}'";
84+
$tableExists = $Driver->query($tableExistsQuery)->rowCount() > 0;
85+
86+
if ($tableExists) {
87+
$sql = preg_replace("/ALTER TABLE `{$tableName}`.*?;/is", "", $sql);
88+
}
89+
}
90+
6491
// execute query
6592
$Driver->exec($sql);
6693

0 commit comments

Comments
 (0)