Skip to content

Commit c2699b5

Browse files
committed
#1759 - Added validation on exists database before created for MySQLi and Postgre
1 parent cc60dad commit c2699b5

2 files changed

Lines changed: 28 additions & 1 deletion

File tree

system/Database/MySQLi/Forge.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ class Forge extends \CodeIgniter\Database\Forge
4949
*
5050
* @var string
5151
*/
52-
protected $createDatabaseStr = 'CREATE DATABASE %s CHARACTER SET %s COLLATE %s';
52+
protected $createDatabaseStr = 'CREATE DATABASE IF NOT EXISTS %s CHARACTER SET %s COLLATE %s';
5353

5454
/**
5555
* DROP CONSTRAINT statement

system/Database/Postgre/Forge.php

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,13 @@
4444
class Forge extends \CodeIgniter\Database\Forge
4545
{
4646

47+
/**
48+
* CHECK DATABASE EXIST statement
49+
*
50+
* @var string
51+
*/
52+
private $checkDatabaseExist = 'SELECT 1 FROM pg_database WHERE datname = %s';
53+
4754
/**
4855
* DROP CONSTRAINT statement
4956
*
@@ -77,6 +84,26 @@ class Forge extends \CodeIgniter\Database\Forge
7784

7885
//--------------------------------------------------------------------
7986

87+
/**
88+
* Create database
89+
*
90+
* @param string $db_name
91+
*
92+
* @return boolean
93+
* @throws \CodeIgniter\Database\Exceptions\DatabaseException
94+
*/
95+
public function createDatabase(string $db_name): bool
96+
{
97+
if ($this->db->query(sprintf($this->checkDatabaseExist, $this->db->escape($db_name)))->getRow() !== null)
98+
{
99+
return true;
100+
}
101+
102+
return parent::createDatabase($db_name);
103+
}
104+
105+
//--------------------------------------------------------------------
106+
80107
/**
81108
* CREATE TABLE attributes
82109
*

0 commit comments

Comments
 (0)