99use orm \DataBase \fields \PrimaryKey ;
1010use orm \DataBase \fields \StringField ;
1111use orm \Exceptions \MigrationException ;
12+ use orm \Query \QueryMemento ;
1213
1314
1415class Migration
@@ -25,8 +26,11 @@ public function __construct($table_fields, $table_name)
2526
2627 public function buildMigrationSqlCode ()
2728 {
29+ $ dbname = QueryMemento::createInstance ()->getStorage ()["dbname " ];
30+ $ query = "create database if not exists ` {$ dbname }` default character set utf8 collate utf8_general_ci; \nuse ` {$ dbname }`; \n" ;
31+ $ query .= "set foreign_key_checks = 0; \n" ;
2832 $ foreign_keys = "" ;
29- $ query = "drop table if exists ` {$ this ->table_name }`; create table ` {$ this ->table_name }` ( \n" ;
33+ $ query . = "drop table if exists ` {$ this ->table_name }`; create table ` {$ this ->table_name }` ( \n" ;
3034 foreach ($ this ->table_fields as $ key => $ field ) {
3135 if ($ field instanceof PrimaryKey) {
3236 $ query .= "` {$ key }` {$ field ->type }( {$ field ->size }) not null primary key auto_increment, \n" ;
@@ -37,8 +41,8 @@ public function buildMigrationSqlCode()
3741 $ property = $ reflection ->getProperty ("table_name " );
3842 $ property ->setAccessible (true );
3943 $ foreign_keys .= "alter table ` {$ this ->table_name }` add constraint ` {$ key }_fk` foreign key (` {$ key }`) " .
40- " references ` {$ property ->getValue ($ table )}` (` {$ field ->field }`) on delete " .
41- "{$ field ->on_delete } on update {$ field ->on_update }; \n" ;
44+ " references ` {$ property ->getValue ($ table )}` (` {$ field ->field }`) on delete " .
45+ "{$ field ->on_delete } on update {$ field ->on_update }; \n" ;
4246 $ property ->setAccessible (false );
4347 } elseif ($ field instanceof StringField) {
4448 $ query .= "` {$ key }` {$ field ->type }( {$ field ->size }) not null, \n" ;
@@ -48,7 +52,7 @@ public function buildMigrationSqlCode()
4852 throw new MigrationException ("Migration Exception " );
4953 }
5054 }
51- return substr ($ query , 0 , -2 ) . "\n) ENGINE =InnoDB DEFAULT CHARSET =utf8; \n" . $ foreign_keys ;
55+ return substr ($ query , 0 , -2 ) . "\n) engine =InnoDB default charset =utf8; \n" . $ foreign_keys . " set foreign_key_checks = 1; \n" ;
5256 }
5357
5458}
0 commit comments