Example #1
0
 /**
  * Build the Table object from the database table definition.
  * @param $name - the name of the table in the database.
  * @param $db - the PDO Database object.
  * @return Table or null
  * @throws Exception if method is not implemented for this db driver.
  */
 public static function fromDB($name, $db)
 {
     if ($db === null) {
         return null;
     }
     $ret = new Table($name, null, $db);
     if ($ret->exists()) {
         $dbtype = $db->getAttribute(\PDO::ATTR_DRIVER_NAME);
         switch ($dbtype) {
             case 'mysql':
                 $sql = "SHOW COLUMNS FROM {$name}";
                 $resultSet = $db->query($sql);
                 $results = $resultSet->fetchAll(\PDO::FETCH_ASSOC);
                 foreach ($results as $field) {
                     $matches = array();
                     $regresult = preg_match("/(\\w+)\\((\\d+)\\)/", $field['Type'], $matches);
                     $realType = '';
                     if ($regresult == 0 || $regresult == false) {
                         $realType = $field['Type'];
                         $realLen = null;
                     } else {
                         $realType = $matches[1];
                         $realLen = (int) $matches[2];
                     }
                     $ret->addField($field['Field'], $realType, $realLen, $field['Null'] == 'YES' ? Table::NULLABLE : Table::NOT_NULL, $field['Default'], $field['Key'] == 'PRI' ? true : false, $field['Key'] == 'UNI' ? 'UNIQUE ' . strtoupper($field['Extra']) : ($field['Extra'] == '' ? null : strtoupper($field['Extra'])));
                 }
                 break;
             default:
                 throw new \Exception('Method (fromDB) not implemented for this driver: ' . $dbtype);
         }
         return $ret;
     }
     return null;
 }