@@ -9,6 +9,11 @@ class Table
99 */
1010 private $ name ;
1111
12+ /**
13+ * @var bool
14+ */
15+ private $ ifNotExists ;
16+
1217 /**
1318 * @var string
1419 */
@@ -70,6 +75,22 @@ public function getName()
7075 return $ this ->name ;
7176 }
7277
78+ /**
79+ * @return bool
80+ */
81+ public function isIfNotExists ()
82+ {
83+ return $ this ->ifNotExists ;
84+ }
85+
86+ /**
87+ * @param bool $ifNotExists
88+ */
89+ public function setIfNotExists ($ ifNotExists )
90+ {
91+ $ this ->ifNotExists = $ ifNotExists ;
92+ }
93+
7394 /**
7495 * @return string
7596 */
@@ -324,7 +345,13 @@ public function generatePrimaryKeyCreationScript()
324345
325346 $ primaryKeys = [];
326347 foreach ($ this ->primaryKeys as $ primaryKeyColumn ) {
327- $ primaryKeys [] = sprintf ('`%s` ' , $ primaryKeyColumn ->getName ());
348+ if ($ primaryKeyColumn ->getPrimaryKeyLength ()) {
349+ $ primaryKey = sprintf ('`%s`(%s) ' , $ primaryKeyColumn ->getName (), $ primaryKeyColumn ->getPrimaryKeyLength ());
350+ } else {
351+ $ primaryKey = sprintf ('`%s` ' , $ primaryKeyColumn ->getName ());
352+ }
353+
354+ $ primaryKeys [] = $ primaryKey ;
328355 }
329356
330357 return sprintf ('PRIMARY KEY (%s) ' , implode (', ' , $ primaryKeys ));
@@ -369,6 +396,12 @@ public function generateCreationScript($ignoreAutoIncrement = false, $sortKeys =
369396
370397 $ tableOptions = [];
371398
399+ if ($ this ->ifNotExists ) {
400+ $ ifNotExists = ' IF NOT EXISTS ' ;
401+ } else {
402+ $ ifNotExists = '' ;
403+ }
404+
372405 if ($ this ->engine ) {
373406 $ tableOptions [] = sprintf ('ENGINE=%s ' , $ this ->engine );
374407 }
@@ -387,6 +420,6 @@ public function generateCreationScript($ignoreAutoIncrement = false, $sortKeys =
387420 $ implodedTableOptions = ' ' . $ implodedTableOptions ;
388421 }
389422
390- return trim (sprintf ('CREATE TABLE `%s` (%s %s%s)%s; ' , $ this ->name , PHP_EOL , implode (', ' . PHP_EOL . ' ' , $ tableDefinitions ), PHP_EOL , $ implodedTableOptions ));
423+ return trim (sprintf ('CREATE TABLE%s `%s` (%s %s%s)%s; ' , $ ifNotExists , $ this ->name , PHP_EOL , implode (', ' . PHP_EOL . ' ' , $ tableDefinitions ), PHP_EOL , $ implodedTableOptions ));
391424 }
392425}
0 commit comments