Skip to content

Commit

Permalink
DBImport and Migration Update
Browse files Browse the repository at this point in the history
  • Loading branch information
Fredrick Peter committed May 7, 2023
1 parent 03fa044 commit e5afeca
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 85 deletions.
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ Prior to installing `php-orm-database` get the [Composer](https://getcomposer.or
**Step 1** — update your `composer.json`:
```composer.json
"require": {
"peterson/php-orm-database": "^3.1.3"
"peterson/php-orm-database": "^3.1.4"
}
```

Expand Down Expand Up @@ -1207,8 +1207,6 @@ $response = $import->DatabaseImport('orm.sql');
</details>

## Update Env Variable
<details><summary>Read more...</summary>

- You can use this class to import .sql into a database programatically

| Params | Description |
Expand All @@ -1225,10 +1223,12 @@ OrmDotEnv::updateENV('DB_PASSWORD', 'newPassword');
OrmDotEnv::updateENV('APP_DEBUG', false);
OrmDotEnv::updateENV('DB_CHARSET', 'utf8', false);
or
dot_env()->updateENV('DB_CHARSET', 'utf8', false);
Returns - Boolean
true|false
```
</details>

## Collation And Charset
- Collation and Charset Data `listing`
Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
},
"extra": {
"branch-alias": {
"dev-main": "3.1.3-dev"
"dev-main": "3.1.4-dev"
}
},
"minimum-stability": "stable",
Expand Down
99 changes: 29 additions & 70 deletions src/DBImport.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,26 +14,24 @@ class DBImport extends DB{
use DBImportTrait;

private $db_connection;
private $error;
private $message;
private $realpath;
private $template;
private $array = [];
public $error;
public $message;

/**
* Construct Instance of Database
*/
public function __construct() {
parent::__construct();

$this->error = self::ERROR_404;
$this->db_connection = $this->getConnection();
}

/**
* Database Importation
* @param string path_to_sql
*
* @return
* @return object\builder\Database\DatabaseImport
*/
public function DatabaseImport($path_to_sql = NULL)
{
Expand All @@ -42,83 +40,42 @@ public function DatabaseImport($path_to_sql = NULL)
/**
* If SQL file does'nt exists
*/
if(!file_exists($this->realpath) || is_dir($this->realpath))
{
return [
'response' => self::ERROR_404,
'message' => "Failed to open stream: `{$path_to_sql}` does'nt exist."
];

if(!file_exists($this->realpath) || is_dir($this->realpath)){
$this->message = "Failed to open stream: `{$path_to_sql}` does'nt exist.";
} else{

// read a file into an array
$readFile = file($this->realpath);

// is readable
if(!$this->isReadable($readFile))
{
return [
'response' => self::ERROR_404,
'message' => "Failed to read file or empty data."
];
if(!$this->isReadable($readFile)){
$this->message = "Failed to read file or empty data.";
} else{

// Begin our final importation
foreach($readFile as $key => $query)
{
// skip if its a comment
if($this->isComment($query))
continue;

//Add to the current segment
$this->template .= $query;

// Check if it's a query
if($this->isQuery($query))
{
// check if connection test is okay
if($this->DBConnect()){
try{
//Query the database
$this->query($this->template)->execute();

} catch(PDOException $e){
// check if connection test is okay
if($this->DBConnect()){
try{
// connection driver
$Driver = $this->connection['driver'];

// get error msg
$errorMsg = $e->getMessage();
// get content
$sql = file_get_contents($this->realpath);

if($errorMsg != '0'){
if(
strpos($errorMsg, "Multiple primary key defined") === false
&& strpos($errorMsg, "Duplicate entry") === false){
// execute query
$Driver->exec($sql);

$this->message = "- Performing query: <strong style='color: #000'>{$errorMsg}</strong>";
$this->array[] = $this->message;
}
$this->error = self::ERROR_400;
}
}
}else{
$this->message = $this->db_connection['message'];
$this->array[] = $this->message;
$this->error = $this->db_connection['status'];
break;
}

// Set the template to an empty string
$this->template = '';
$this->error = self::ERROR_200;
$this->message = "- Database has been imported successfully.";
} catch(PDOException $e){
$this->message = "- Performing query: <strong style='color: #000'>{$e->getMessage()}</strong>";
$this->error = self::ERROR_400;
}
} else{
$this->message = $this->db_connection['message'];
}
}
}

// successful and no errors
if(count($this->array) === 0 && $this->db_connection['status'] == self::ERROR_200){
$this->error = self::ERROR_200;
$this->message = "- Database has been imported successfully.";
$this->array[0] = $this->message;
}

/*
| ----------------------------------------------------------------------------
| Database importation use. Below are the response code
Expand All @@ -128,9 +85,11 @@ public function DatabaseImport($path_to_sql = NULL)
| if ->response === 200 (Success importing to database
*/

return [
'response' => $this->error,
'message' => $this->array
return (object) [
'response' => $this->error,
'message' => is_array($this->message)
? implode('\n<br>', $this->message)
: $this->message
];
}

Expand Down
18 changes: 8 additions & 10 deletions src/Migrations/Traits/TableStructureTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -223,12 +223,11 @@ private function createTriggers()
--
-- Trigger to set created_at timestamp on insert
--
CREATE TRIGGER {$this->tableName}_created_at
BEFORE INSERT ON {$this->tableName}
FOR EACH ROW
DROP TRIGGER IF EXISTS `{$this->tableName}_created_at`;
CREATE TRIGGER `{$this->tableName}_created_at` BEFORE INSERT ON `{$this->tableName}` FOR EACH ROW
BEGIN
IF (SELECT COUNT(*) FROM information_schema.columns
WHERE table_name = '{$this->tableName}'
IF (SELECT COUNT(*) FROM information_schema.columns
WHERE table_name = '{$this->tableName}'
AND column_name = 'created_at') > 0 THEN
SET NEW.created_at = IFNULL(NEW.created_at, NOW());
SET NEW.updated_at = NOW();
Expand All @@ -242,12 +241,11 @@ private function createTriggers()
--
-- Trigger to update updated_at timestamp on update
--
CREATE TRIGGER {$this->tableName}_updated_at
BEFORE UPDATE ON {$this->tableName}
FOR EACH ROW
DROP TRIGGER IF EXISTS `{$this->tableName}_updated_at`;
CREATE TRIGGER `{$this->tableName}_updated_at` BEFORE UPDATE ON `{$this->tableName}` FOR EACH ROW
BEGIN
IF (SELECT COUNT(*) FROM information_schema.columns
WHERE table_name = '{$this->tableName}'
IF (SELECT COUNT(*) FROM information_schema.columns
WHERE table_name = '{$this->tableName}'
AND column_name = 'updated_at') > 0 THEN
SET NEW.updated_at = NOW();
END IF;
Expand Down

0 comments on commit e5afeca

Please sign in to comment.