Ignore:
Timestamp:
Dec 22, 2020, 11:34:19 PM (4 years ago)
Author:
chronos
Message:
  • Added: Install and uninstall modules models persistence using abstract classes.
File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/Packages/Common/AppModule.php

    r887 r889  
    184184    $this->Models[get_class($Model)] = $Model;
    185185  }
     186
     187  function InstallModel(ModelDesc $ModelDesc)
     188  {
     189    $Query = 'CREATE TABLE IF NOT EXISTS `'.$ModelDesc->Name.'` ('."\n";
     190    $Query = '  `'.$ModelDesc->PrimaryKey.'` int(11) NOT NULL AUTO_INCREMENT,'."\n";
     191    foreach ($ModelDesc->Columns as $Column)
     192    {
     193      $Query .= "  `".$Column->Name."` ";
     194      if ($Column->Type == ModelColumnType::Integer) $Query .= 'int(11)';
     195      else if ($Column->Type == ModelColumnType::String) $Query .= 'varchar(255)';
     196      else if ($Column->Type == ModelColumnType::Float) $Query .= 'varchar(255)';
     197      else if ($Column->Type == ModelColumnType::Text) $Query .= 'text';
     198      else if ($Column->Type == ModelColumnType::DateTime) $Query .= 'datetime';
     199      else if ($Column->Type == ModelColumnType::Reference) $Query .= 'int(11)';
     200
     201      if ($Column->Nullable) $Query .= '';
     202        else $Query .= ' NOT NULL';
     203
     204      $Query .= ' COLLATE utf8_general_ci';
     205
     206      if ($Column->HasDefault)
     207      {
     208        if ($Column->Default == null)
     209          $Query .= ' DEFAULT NULL';
     210        $Query .= ' DEFAULT '.$Column->GetDefault();
     211      }
     212      $Query .= ",\n";
     213    }
     214    $Query .= '  PRIMARY KEY (`'.$ModelDesc->PrimaryKey.'`),';
     215    foreach ($ModelDesc->Columns as $Column)
     216    {
     217      if ($Column->Type == ModelColumnType::Reference)
     218        $Query .= '  KEY `'.$Column->Name.'` (`'.$Column->Name.'`)'."\n";
     219      else if ($Column->Unique)
     220        $Query .= '  UNIQUE KEY `'.$Column->Name.'` (`'.$Column->Name.'`)'."\n";
     221    }
     222
     223    $Query .= ") ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;";
     224    $I = 1;
     225    foreach ($ModelDesc->Columns as $Column)
     226    {
     227      if ($Column->Type == ModelColumnType::Reference)
     228        $Query .= "ALTER TABLE `".$ModelDesc->Name."` ".
     229        "ADD CONSTRAINT `".$ModelDesc->Name."_ibfk_".$I."` FOREIGN KEY (`".$Column->Name."`) REFERENCES `".$Column->RefTable."` (`Id`);";
     230    }
     231    $this->Database->query($Query);
     232  }
     233
     234  function UninstallModel(ModelDesc $ModelDesc)
     235  {
     236    $this->Database->query('DROP TABLE `'.$ModelDesc->Name.'`');
     237  }
    186238}
    187239
Note: See TracChangeset for help on using the changeset viewer.