|
14 | 14 | namespace CodeIgniter\Database\SQLSRV; |
15 | 15 |
|
16 | 16 | use CodeIgniter\Database\BaseConnection; |
| 17 | +use CodeIgniter\Database\Exceptions\DatabaseException; |
17 | 18 | use CodeIgniter\Database\Forge as BaseForge; |
| 19 | +use Throwable; |
18 | 20 |
|
19 | 21 | /** |
20 | 22 | * Forge for SQLSRV |
@@ -42,7 +44,7 @@ class Forge extends BaseForge |
42 | 44 | * |
43 | 45 | * @var string |
44 | 46 | */ |
45 | | - protected $createDatabaseIfStr = "DECLARE @DBName VARCHAR(255) = '%s'\nDECLARE @SQL VARCHAR(max) = 'IF DB_ID( ''' + @DBName + ''' ) IS NULL CREATE DATABASE ' + @DBName\nEXEC( @SQL )"; |
| 47 | + protected $createDatabaseIfStr = "DECLARE @DBName VARCHAR(255) = '%s'\nDECLARE @SQL VARCHAR(max) = 'IF DB_ID( ''' + @DBName + ''' ) IS NULL CREATE DATABASE %s'\nEXEC( @SQL )"; |
46 | 48 |
|
47 | 49 | /** |
48 | 50 | * CREATE DATABASE IF statement |
@@ -119,6 +121,53 @@ public function __construct(BaseConnection $db) |
119 | 121 | $this->dropIndexStr = 'DROP INDEX %s ON ' . $this->db->escapeIdentifiers($this->db->schema) . '.%s'; |
120 | 122 | } |
121 | 123 |
|
| 124 | + /** |
| 125 | + * Create database |
| 126 | + * |
| 127 | + * @param bool $ifNotExists Whether to add IF NOT EXISTS condition |
| 128 | + * |
| 129 | + * @throws DatabaseException |
| 130 | + */ |
| 131 | + public function createDatabase(string $dbName, bool $ifNotExists = false): bool |
| 132 | + { |
| 133 | + if ($ifNotExists) { |
| 134 | + $sql = sprintf( |
| 135 | + $this->createDatabaseIfStr, |
| 136 | + $dbName, |
| 137 | + $this->db->escapeIdentifier($dbName) |
| 138 | + ); |
| 139 | + } else { |
| 140 | + $sql = sprintf( |
| 141 | + $this->createDatabaseStr, |
| 142 | + $this->db->escapeIdentifier($dbName) |
| 143 | + ); |
| 144 | + } |
| 145 | + |
| 146 | + try { |
| 147 | + if (! $this->db->query($sql)) { |
| 148 | + // @codeCoverageIgnoreStart |
| 149 | + if ($this->db->DBDebug) { |
| 150 | + throw new DatabaseException('Unable to create the specified database.'); |
| 151 | + } |
| 152 | + |
| 153 | + return false; |
| 154 | + // @codeCoverageIgnoreEnd |
| 155 | + } |
| 156 | + |
| 157 | + if (isset($this->db->dataCache['db_names'])) { |
| 158 | + $this->db->dataCache['db_names'][] = $dbName; |
| 159 | + } |
| 160 | + |
| 161 | + return true; |
| 162 | + } catch (Throwable $e) { |
| 163 | + if ($this->db->DBDebug) { |
| 164 | + throw new DatabaseException('Unable to create the specified database.', 0, $e); |
| 165 | + } |
| 166 | + |
| 167 | + return false; // @codeCoverageIgnore |
| 168 | + } |
| 169 | + } |
| 170 | + |
122 | 171 | /** |
123 | 172 | * CREATE TABLE attributes |
124 | 173 | */ |
|
0 commit comments