/**
  * Transform a model descriptor to a table descriptor.
  *
  * @param ModelDescriptor $descriptor
  * @return RecessTableDescriptor
  */
 function modelToTableDescriptor(ModelDescriptor $descriptor)
 {
     Library::import('recess.database.pdo.RecessTableDescriptor');
     Library::import('recess.database.pdo.RecessColumnDescriptor');
     $tableDescriptor = new RecessTableDescriptor();
     $tableDescriptor->name = $descriptor->getTable();
     foreach ($descriptor->properties as $property) {
         $tableDescriptor->addColumn($property->name, $property->type, true, $property->isPrimaryKey, array(), $property->isAutoIncrement ? array('autoincrement' => true) : array());
     }
     return $tableDescriptor;
 }
 /**
  * Sanity check and semantic sugar from higher level
  * representation of table pushed down to the RDBMS
  * representation of the table.
  *
  * @param string $table
  * @param RecessTableDescriptor $descriptor
  */
 function cascadeTableDescriptor($table, RecessTableDescriptor $descriptor)
 {
     $sourceDescriptor = $this->getTableDescriptor($table);
     if (!$sourceDescriptor->tableExists) {
         $descriptor->tableExists = false;
         return $descriptor;
     }
     $sourceColumns = $sourceDescriptor->getColumns();
     $errors = array();
     foreach ($descriptor->getColumns() as $column) {
         if (isset($sourceColumns[$column->name])) {
             if ($column->isPrimaryKey && !$sourceColumns[$column->name]->isPrimaryKey) {
                 $errors[] = 'Column "' . $column->name . '" is not the primary key in table ' . $table . '.';
             }
             if ($sourceColumns[$column->name]->type != $column->type) {
                 $errors[] = 'Column "' . $column->name . '" type "' . $column->type . '" does not match database column type "' . $sourceColumns[$column->name]->type . '".';
             }
         } else {
             $errors[] = 'Column "' . $column->name . '" does not exist in table ' . $table . '.';
         }
     }
     if (!empty($errors)) {
         throw new RecessException(implode(' ', $errors), get_defined_vars());
     } else {
         return $sourceDescriptor;
     }
 }
 /**
  * Given a Table Definition, return the CREATE TABLE SQL statement
  * in the Sqlite's syntax.
  *
  * @param RecessTableDescriptor $tableDescriptor
  */
 function createTableSql(RecessTableDescriptor $definition)
 {
     $sql = 'CREATE TABLE ' . $definition->name;
     $columnSql = null;
     foreach ($definition->getColumns() as $column) {
         if (isset($columnSql)) {
             $columnSql .= ', ';
         }
         $columnSql .= "\n\t" . $column->name . ' ' . strtoupper($column->type);
         if ($column->isPrimaryKey) {
             $columnSql .= ' PRIMARY KEY';
             if (isset($column->options['autoincrement'])) {
                 $columnSql .= ' AUTOINCREMENT';
             }
         }
     }
     $columnSql .= "\n";
     return $sql . ' (' . $columnSql . ')';
 }