Наследование: extends Object
Пример #1
0
 /**
  * Overwritten to change $this->path when it's been specifically given in the first parameter
  * CakePHP has a problem where it would override the path if it's a plugin, without checking if it was specified
  */
 public function build($data)
 {
     parent::build($data);
     if (!empty($data['path'])) {
         $this->path = $data['path'];
     }
 }
Пример #2
0
 /**
  * Update database with Schema object
  * Should be called via the run method
  *
  * @access private
  */
 function __update(&$Schema, $table = null)
 {
     $db = ConnectionManager::getDataSource($this->Schema->connection);
     $this->out(__('Comparing Database to Schema...'));
     $options = array();
     if (isset($this->params['force'])) {
         $options['models'] = false;
     }
     $Old = $this->Schema->read($options);
     $compare = $this->Schema->compare($Old, $Schema);
     $contents = array();
     if (empty($table)) {
         foreach ($compare as $table => $changes) {
             $contents[$table] = $db->alterSchema(array($table => $changes), $table);
         }
     } elseif (isset($compare[$table])) {
         $contents[$table] = $db->alterSchema(array($table => $compare[$table]), $table);
     }
     if (empty($contents)) {
         $this->out(__('Schema is up to date.'));
         $this->_stop();
     }
     $this->out("\n" . __('The following statements will run.'));
     $this->out(array_map('trim', $contents));
     if ('y' == $this->in(__('Are you sure you want to alter the tables?'), array('y', 'n'), 'n')) {
         $this->out();
         $this->out(__('Updating Database...'));
         $this->__run($contents, 'update', $Schema);
     }
     $this->out(__('End update.'));
 }
Пример #3
0
 /**
  * Setup DataSource Object and get tables information
  *
  * @param string $datasouce
  * @return bool
  */
 function _setupDataSource($datasouce)
 {
     // get datasource
     $this->DataSource =& ConnectionManager::getDataSource($datasouce);
     if (!is_subclass_of($this->DataSource, 'DboSource')) {
         // DataSource is not subclass of DboSource
         return false;
     }
     // get datasouces tables
     $schema = $this->Schema->read(array('connection' => $this->DataSource->configKeyName, 'models' => false));
     $this->_tables = $schema['tables'];
     return true;
 }
 /**
  * Return CakeSchema object for given Schema name
  *
  * @return CakeSchema
  */
 protected function _schema()
 {
     if ($this->_Schema) {
         return $this->_Schema;
     }
     $db = ConnectionManager::getDataSource($this->useDbConfig);
     $this->_Schema = new CakeSchema(array('connection' => $db));
     $this->_Schema->build(array($this->_tableName() => $this->_schema));
     Cache::drop('_cake_model_');
     $db->cacheSources = false;
     $db->reconnect();
     return $this->_Schema;
 }
Пример #5
0
 /**
  * Update database with Schema object
  * Should be called via the run method
  *
  * @param CakeSchema &$Schema The schema instance
  * @param string     $table   The table name.
  *
  * @return void
  */
 protected function _update(&$Schema, $table = NULL)
 {
     $db = ConnectionManager::getDataSource($this->Schema->connection);
     $this->out(__d('cake_console', 'Comparing Database to Schema...'));
     $options = array();
     if (isset($this->params['force'])) {
         $options['models'] = FALSE;
     }
     $Old = $this->Schema->read($options);
     $compare = $this->Schema->compare($Old, $Schema);
     $contents = array();
     if (empty($table)) {
         foreach ($compare as $table => $changes) {
             if (isset($compare[$table]['create'])) {
                 $contents[$table] = $db->createSchema($Schema, $table);
             } else {
                 $contents[$table] = $db->alterSchema(array($table => $compare[$table]), $table);
             }
         }
     } elseif (isset($compare[$table])) {
         if (isset($compare[$table]['create'])) {
             $contents[$table] = $db->createSchema($Schema, $table);
         } else {
             $contents[$table] = $db->alterSchema(array($table => $compare[$table]), $table);
         }
     }
     if (empty($contents)) {
         $this->out(__d('cake_console', 'Schema is up to date.'));
         return $this->_stop();
     }
     $this->out("\n" . __d('cake_console', 'The following statements will run.'));
     $this->out(array_map('trim', $contents));
     if (!empty($this->params['yes']) || $this->in(__d('cake_console', 'Are you sure you want to alter the tables?'), array('y', 'n'), 'n') === 'y') {
         $this->out();
         $this->out(__d('cake_console', 'Updating Database...'));
         $this->_run($contents, 'update', $Schema);
     }
     $this->out(__d('cake_console', 'End update.'));
 }
Пример #6
0
 /**
  * test comparing '' and null and making sure they are different.
  *
  * @return void
  */
 public function testCompareEmptyStringAndNull()
 {
     $One = new CakeSchema(array('posts' => array('id' => array('type' => 'integer', 'null' => false, 'default' => null, 'key' => 'primary'), 'name' => array('type' => 'string', 'null' => false, 'default' => ''))));
     $Two = new CakeSchema(array('posts' => array('id' => array('type' => 'integer', 'null' => false, 'default' => null, 'key' => 'primary'), 'name' => array('type' => 'string', 'null' => false, 'default' => null))));
     $compare = $One->compare($Two);
     $expected = array('posts' => array('change' => array('name' => array('type' => 'string', 'null' => false, 'default' => null))));
     $this->assertEquals($expected, $compare);
 }
Пример #7
0
 protected function _getTables()
 {
     $_Schema = new CakeSchema();
     $database = $_Schema->read();
     $tables = array();
     foreach ($database['tables'] as $tableName => $schema) {
         if (in_array($tableName, $this->ignoredTables) || empty($tableName) || $tableName === 'missing') {
             continue;
         }
         $tables[$tableName] = $schema;
     }
     return $tables;
 }
Пример #8
0
 public function __construct($options = array())
 {
     parent::__construct();
 }
Пример #9
0
 /**
  * afterSave method
  *
  * If a default has just been saved check the db and update the table if the db default is different.
  *
  * @return void
  * @access public
  */
 function afterSave()
 {
     if (isset($this->data['Enum']['default']) && $this->data['Enum']['default']) {
         $conditions['type'] = isset($this->data['Enum']['type']) ? $this->data['Enum']['type'] : $this->field('type');
         $conditions['NOT']['Enum.id'] = $this->id;
         $this->updateAll(array('default' => 'false'), $conditions);
         $default = isset($this->data['Enum']['value']) ? $this->data['Enum']['value'] : $this->field('value');
         if ($default) {
             $db =& ConnectionManager::getDataSource($this->useDbConfig);
             App::import('Model', 'CakeSchema');
             $Schema = new CakeSchema(array('connection' => $this->useDbConfig));
             $update = $current = $Schema->read(array('models' => false));
             list($model, $field) = explode('.', $conditions['type']);
             $table = Inflector::tableize($model);
             if (isset($update['tables'][$table][$field])) {
                 $update['tables'][$table][$field]['default'] = $default;
                 $update['tables'][$table][$field]['null'] = true;
                 $compare = $Schema->compare($current, $update);
                 foreach ($compare as $table => $changes) {
                     $db->execute($db->alterSchema(array($table => $changes), $table));
                 }
                 Cache::delete($this->useDbConfig . '_' . $table, '_cake_model_');
             }
         }
     }
 }
Пример #10
0
 /**
  * test alterSchema on two tables.
  *
  * @return void
  */
 public function testAlteringTwoTables()
 {
     $schema1 = new CakeSchema(array('name' => 'AlterTest1', 'connection' => 'test', 'altertest' => array('id' => array('type' => 'integer', 'null' => false, 'default' => 0), 'name' => array('type' => 'string', 'null' => false, 'length' => 50)), 'other_table' => array('id' => array('type' => 'integer', 'null' => false, 'default' => 0), 'name' => array('type' => 'string', 'null' => false, 'length' => 50))));
     $schema2 = new CakeSchema(array('name' => 'AlterTest1', 'connection' => 'test', 'altertest' => array('id' => array('type' => 'integer', 'null' => false, 'default' => 0), 'field_two' => array('type' => 'string', 'null' => false, 'length' => 50)), 'other_table' => array('id' => array('type' => 'integer', 'null' => false, 'default' => 0), 'field_two' => array('type' => 'string', 'null' => false, 'length' => 50))));
     $result = $this->db->alterSchema($schema2->compare($schema1));
     $this->assertEquals(2, substr_count($result, 'field_two'), 'Too many fields');
     $this->assertFalse(strpos(';ALTER', $result), 'Too many semi colons');
 }
 /**
  * Runs sql from _create() or _update()
  *
  * @param array $contents
  * @param string $event
  * @param CakeSchema $Schema
  * @return void
  */
 protected function _run($contents, $event, &$Schema)
 {
     if (empty($contents)) {
         $this->err(__d('cake_console', 'Sql could not be run'));
         return;
     }
     Configure::write('debug', 2);
     $db = ConnectionManager::getDataSource($this->Schema->connection);
     foreach ($contents as $table => $sql) {
         if (empty($sql)) {
             $this->out(__d('cake_console', '%s is up to date.', $table));
         } else {
             if ($this->_dry === true) {
                 $this->out(__d('cake_console', 'Dry run for %s :', $table));
                 $this->out($sql);
             } else {
                 if (!$Schema->before(array($event => $table))) {
                     return false;
                 }
                 $error = null;
                 try {
                     $db->execute($sql);
                 } catch (PDOException $e) {
                     $error = $table . ': ' . $e->getMessage();
                 }
                 $Schema->after(array($event => $table, 'errors' => $error));
                 if (!empty($error)) {
                     $this->err($error);
                 } else {
                     $this->out(__d('cake_console', '%s updated.', $table));
                 }
             }
         }
     }
 }
Пример #12
0
 /**
  * Runs sql from _createSchema()
  *
  * NOTE: adapted from the schema shell lib/Cake/Console/Command/SchemaShell.php
  *
  * @param array $contents
  * @param string $event
  * @param CakeSchema $Schema
  * @return string
  */
 protected function _runSchema($db, $contents, $event, &$Schema)
 {
     $out = '';
     if (empty($contents)) {
         $this->error('Sql could not be run');
         return false;
     }
     foreach ($contents as $table => $sql) {
         if (empty($sql)) {
             $out .= sprintf("%s is up to date.\n", $table);
         } else {
             if (!$Schema->before(array($event => $table))) {
                 return false;
             }
             $error = null;
             try {
                 $db->execute($sql);
             } catch (PDOException $e) {
                 $error = $table . ': ' . $e->getMessage();
             }
             $Schema->after(array($event => $table, 'errors' => $error));
             if (!empty($error)) {
                 $this->error($error);
                 return false;
             } else {
                 $out .= sprintf("%s updated\n", $table);
             }
         }
     }
     return $out;
 }
Пример #13
0
 function fixture($model, $useTable = null)
 {
     if (!class_exists('CakeSchema')) {
         App::import('Model', 'Schema');
     }
     $out = "\nclass {$model}Fixture extends CakeTestFixture {\n";
     if (!$useTable) {
         $useTable = Inflector::tableize($model);
     } else {
         //$out .= "\tvar \$table = '$useTable';\n";
     }
     $schema = new CakeSchema();
     $data = $schema->read(array('models' => false, 'connection' => $this->useDbConfig));
     if (!isset($data['tables'][$useTable])) {
         return false;
     }
     $out .= "\tvar \$name = '{$model}';\n";
     $out .= "\tvar \$import = array('table' => '{$useTable}', 'records' => true, 'connection' => '{$this->useDbConfig}');\n";
     $tempModel = ClassRegistry::init($model);
     $tempModel->recursive = -1;
     $count = $tempModel->find('count');
     $response = '';
     $example = 'Q';
     while ($response == '') {
         $this->out('');
         $response = $this->in("'{$model}' has " . $count . " records. Set limit number?" . "\nLimit number or [A]ll" . "\n[Q]uit", null, $example);
         if (strtoupper($response) === 'Q') {
             $this->out('Fake Aborted');
             return false;
         }
     }
     if (!is_numeric($response) && strtoupper($response) !== 'A') {
         $this->out(__('You have made an invalid selection. Please choose a command to execute by entering A or Q or number.', true));
         $this->execute();
     }
     if (is_numeric($response) && $response > $count) {
         $this->out(__('The number that you selected is more than the number of records. Please try again.', true));
         $this->execute();
     }
     $query = array();
     if (is_numeric($response)) {
         $query['limit'] = $response;
     }
     $results = $tempModel->find('all', $query);
     $records = array();
     foreach ($results as $result) {
         $record = array();
         foreach ($result[$model] as $field => $value) {
             $record[] = "\t\t'{$field}' => '{$value}'";
         }
         $records[] = "array(\n" . implode(",\n", $record) . ")";
     }
     $records = implode(",\n", $records);
     $out .= "\tvar \$records = array(\n{$records}\n\t);\n";
     $out .= "}\n";
     $path = TESTS . DS . 'fixtures' . DS;
     if (isset($this->plugin)) {
         $pluginPath = 'plugins' . DS . Inflector::underscore($this->plugin) . DS;
         $path = APP . $pluginPath . 'tests' . DS . 'fixtures' . DS;
     }
     $filename = Inflector::underscore($model) . '_fixture.php';
     $header = '$Id';
     $content = "<?php \n/* SVN FILE: {$header}\$ */\n/* " . $model . " Fixture generated on: " . date('Y-m-d H:i:s') . " : " . time() . "*/\n{$out}?>";
     $this->out("\nBaking test fixture for {$model}...");
     if ($this->createFile($path . $filename, $content)) {
         return str_replace("\t\t", "\t\t\t", $records);
     }
     return false;
 }
 function admin_export($id = null)
 {
     $this->layout = null;
     $this->autoRender = false;
     if (!$id) {
         $this->Session->setFlash(__('Invalid Node Schema', true));
         $this->redirect(array('action' => 'index'));
     }
     $this->NodeSchema->recursive = -1;
     $this->set('node_schemas', $node_schemas = $this->NodeSchema->read(null, $id));
     App::Import('CakeSchema');
     $CakeSchema = new CakeSchema();
     //debug($CakeSchema->tables);
     //debug($CakeSchema->read(array('default', 'test')));
     // The above only works for tables that have models, our models are only instantiated when needed in memory
     $db =& ConnectionManager::getDataSource($node_schemas['NodeSchema']['datasource']);
     //$tables = array();
     $Model = new Model(null, $node_schemas['NodeSchema']['table_name'], $node_schemas['NodeSchema']['datasource']);
     $Model->name = $Model->alias = Inflector::classify($node_schemas['NodeSchema']['table_name']);
     $Object = ClassRegistry::init(array('class' => Inflector::pluralize($Model->name), 'ds' => $node_schemas['NodeSchema']['datasource']));
     // These cause issues for one reason or another
     unset($Object->tableToModel);
     unset($Object->__associationKeys);
     unset($Object->__associations);
     unset($Object->_findMethods);
     // The rest here just aren't needed, but don't cause any issues (not sure if it makes the export any faster, but makes the import php file smaller)
     unset($Object->Behaviors);
     unset($Object->useCache);
     unset($Object->cacheSources);
     unset($Object->alias);
     unset($Object->recursive);
     unset($Object->primaryKey);
     unset($Object->table);
     unset($Object->useTable);
     unset($Object->displayField);
     unset($Object->useDbConfig);
     // This may eventually get used, if I can figure how to set it so it writes to the file
     // This is weird and doesn't even seem right, but it renames the property and works
     $Object->{$node_schemas}['NodeSchema']['table_name'] = $Object->_schema;
     unset($Object->_schema);
     $CakeSchema->path = $this->nodeSchemaPath;
     $CakeSchema->file = $node_schemas['NodeSchema']['table_name'] . '.php';
     $CakeSchema->write($Object);
     if (file_exists($this->nodeSchemaPath . DS . $CakeSchema->file)) {
         $file = $this->nodeSchemaPath . DS . $CakeSchema->file;
         header("Content-Type: application/octet-stream");
         header("Accept-Ranges: bytes");
         header("Content-Length: " . filesize($file));
         header("Content-Disposition: attachment; filename=" . $CakeSchema->file);
         readfile($file);
     } else {
         $this->Session->setFlash(__('Could not export node schema, ensure the path: ' . $this->nodeSchemaPath . ' is writeable by the server.', true));
         $this->redirect(array('action' => 'index'));
     }
 }
Пример #15
0
 public function __construct($options = array())
 {
     parent::__construct();
     $this->renames = array('contact_details' => array('contact_detail_type_id' => 'contact_detail_type'));
 }
Пример #16
0
 /**
  * Builds the tests fixtures for the model and create the file
  *
  * @param string $model the name of the model
  * @param string $useTable table name
  * @return array $records, used in ModelTask::bakeTest() to create $expected
  * @todo move this to a task
  */
 function fixture($model, $useTable = null)
 {
     if (!class_exists('CakeSchema')) {
         App::import('Model', 'Schema');
     }
     $out = "\nclass {$model}Fixture extends CakeTestFixture {\n";
     $out .= "\tvar \$name = '{$model}';\n";
     if (!$useTable) {
         $useTable = Inflector::tableize($model);
     } else {
         $out .= "\tvar \$table = '{$useTable}';\n";
     }
     $schema = new CakeSchema();
     $data = $schema->read(array('models' => false, 'connection' => $this->useDbConfig));
     if (!isset($data['tables'][$useTable])) {
         return false;
     }
     $tables[$model] = $data['tables'][$useTable];
     foreach ($tables as $table => $fields) {
         if (!is_numeric($table) && $table !== 'missing') {
             $out .= "\tvar \$fields = array(\n";
             $records = array();
             if (is_array($fields)) {
                 $cols = array();
                 foreach ($fields as $field => $value) {
                     if ($field != 'indexes') {
                         if (is_string($value)) {
                             $type = $value;
                             $value = array('type' => $type);
                         }
                         $col = "\t\t'{$field}' => array('type'=>'" . $value['type'] . "', ";
                         switch ($value['type']) {
                             case 'float':
                             case 'integer':
                                 $insert = 1;
                                 break;
                             case 'binary':
                             case 'string':
                                 $insert = "Lorem ipsum dolor sit amet";
                                 if (!empty($value['length'])) {
                                     $insert = substr($insert, 0, (int) $value['length'] - 2);
                                 }
                                 $insert = "'{$insert}'";
                                 break;
                             case 'datetime':
                                 $ts = date('Y-m-d H:i:s');
                                 $insert = "'{$ts}'";
                                 break;
                             case 'date':
                                 $ts = date('Y-m-d');
                                 $insert = "'{$ts}'";
                                 break;
                             case 'time':
                                 $ts = date('H:i:s');
                                 $insert = "'{$ts}'";
                                 break;
                             case 'boolean':
                                 $insert = 1;
                                 break;
                             case 'text':
                                 $insert = "'Lorem ipsum dolor sit amet, aliquet feugiat. Convallis morbi fringilla gravida,";
                                 $insert .= "phasellus feugiat dapibus velit nunc, pulvinar eget sollicitudin venenatis cum nullam,";
                                 $insert .= "vivamus ut a sed, mollitia lectus. Nulla vestibulum massa neque ut et, id hendrerit sit,";
                                 $insert .= "feugiat in taciti enim proin nibh, tempor dignissim, rhoncus duis vestibulum nunc mattis convallis.'";
                                 break;
                         }
                         $records[] = "\t\t'{$field}' => {$insert}";
                         unset($value['type']);
                         $col .= implode(', ', $schema->__values($value));
                     } else {
                         $col = "\t\t'indexes' => array(";
                         $props = array();
                         foreach ((array) $value as $key => $index) {
                             $props[] = "'{$key}' => array(" . implode(', ', $schema->__values($index)) . ")";
                         }
                         $col .= implode(', ', $props);
                     }
                     $col .= ")";
                     $cols[] = $col;
                 }
                 $out .= implode(",\n", $cols);
             }
             $out .= "\n\t);\n";
         }
     }
     $records = implode(",\n", $records);
     $out .= "\tvar \$records = array(array(\n{$records}\n\t));\n";
     $out .= "}\n";
     $path = TESTS . DS . 'fixtures' . DS;
     if (isset($this->plugin)) {
         $pluginPath = 'plugins' . DS . Inflector::underscore($this->plugin) . DS;
         $path = APP . $pluginPath . 'tests' . DS . 'fixtures' . DS;
     }
     $filename = Inflector::underscore($model) . '_fixture.php';
     $header = '$Id';
     $content = "<?php \n/* SVN FILE: {$header}\$ */\n/* " . $model . " Fixture generated on: " . date('Y-m-d H:i:s') . " : " . time() . "*/\n{$out}?>";
     $this->out("\nBaking test fixture for {$model}...");
     if ($this->createFile($path . $filename, $content)) {
         return str_replace("\t\t", "\t\t\t", $records);
     }
     return false;
 }
Пример #17
0
    /**
     * Builds the tests fixtures for the model and create the file
     *
     * @param string $model the name of the model
     * @param string $useTable table name
     * @return array $records, used in ModelTask::bakeTest() to create $expected
     * @todo move this to a task
     */
    function fixture($model, $useTable = null)
    {
        if (!class_exists('CakeSchema')) {
            App::import('Model', 'Schema');
        }
        $out = "\nclass {$model}Fixture extends CakeTestFixture {\n";
        $out .= "\tvar \$name = '{$model}';\n";
        if (!$useTable) {
            $useTable = Inflector::tableize($model);
        } else {
            $out .= "\tvar \$table = '{$useTable}';\n";
        }
        $schema = new CakeSchema();
        $data = $schema->read(array('models' => false));
        if (!isset($data['tables'][$useTable])) {
            return false;
        }
        $tables[$model] = $data['tables'][$useTable];
        foreach ($tables as $table => $fields) {
            if (!is_numeric($table) && $table !== 'missing') {
                $out .= "\tvar \$fields = array(\n";
                $records = array();
                if (is_array($fields)) {
                    $cols = array();
                    foreach ($fields as $field => $value) {
                        if ($field != 'indexes') {
                            if (is_string($value)) {
                                $type = $value;
                                $value = array('type' => $type);
                            }
                            $col = "\t\t\t'{$field}' => array('type'=>'" . $value['type'] . "', ";
                            switch ($value['type']) {
                                case 'integer':
                                    $insert = 1;
                                    break;
                                case 'string':
                                    $insert = "Lorem ipsum dolor sit amet";
                                    if (!empty($value['length'])) {
                                        $insert = substr($insert, 0, (int) $value['length'] - 2);
                                    }
                                    $insert = "'{$insert}'";
                                    break;
                                case 'datetime':
                                    $ts = date('Y-m-d H:i:s');
                                    $insert = "'{$ts}'";
                                    break;
                                case 'date':
                                    $ts = date('Y-m-d');
                                    $insert = "'{$ts}'";
                                    break;
                                case 'time':
                                    $ts = date('H:i:s');
                                    $insert = "'{$ts}'";
                                    break;
                                case 'boolean':
                                    $insert = 1;
                                    break;
                                case 'text':
                                    $insert = '\'Lorem ipsum dolor sit amet, aliquet feugiat. Convallis morbi fringilla gravida,
									phasellus feugiat dapibus velit nunc, pulvinar eget sollicitudin venenatis cum nullam,
									vivamus ut a sed, mollitia lectus. Nulla vestibulum massa neque ut et, id hendrerit sit,
									feugiat in taciti enim proin nibh, tempor dignissim, rhoncus duis vestibulum nunc mattis convallis.
									Orci aliquet, in lorem et velit maecenas luctus, wisi nulla at, mauris nam ut a, lorem et et elit eu.
									Sed dui facilisi, adipiscing mollis lacus congue integer, faucibus consectetuer eros amet sit sit,
									magna dolor posuere. Placeat et, ac occaecat rutrum ante ut fusce. Sit velit sit porttitor non enim purus,
									id semper consectetuer justo enim, nulla etiam quis justo condimentum vel, malesuada ligula arcu. Nisl neque,
									ligula cras suscipit nunc eget, et tellus in varius urna odio est. Fuga urna dis metus euismod laoreet orci,
									litora luctus suspendisse sed id luctus ut. Pede volutpat quam vitae, ut ornare wisi. Velit dis tincidunt,
									pede vel eleifend nec curabitur dui pellentesque, volutpat taciti aliquet vivamus viverra, eget tellus ut
									feugiat lacinia mauris sed, lacinia et felis.\'';
                                    break;
                            }
                            $records[] = "\t\t\t'{$field}'  => {$insert}";
                            unset($value['type']);
                            $col .= join(', ', $schema->__values($value));
                        } else {
                            $col = "\t\t\t'indexes' => array(";
                            $props = array();
                            foreach ((array) $value as $key => $index) {
                                $props[] = "'{$key}' => array(" . join(', ', $schema->__values($index)) . ")";
                            }
                            $col .= join(', ', $props);
                        }
                        $col .= ")";
                        $cols[] = $col;
                    }
                    $out .= join(",\n", $cols);
                }
                $out .= "\n\t\t\t);\n";
            }
        }
        $records = join(",\n", $records);
        $out .= "\tvar \$records = array(array(\n{$records}\n\t\t\t));\n";
        $out .= "}\n";
        $path = TESTS . DS . 'fixtures' . DS;
        if (isset($this->plugin)) {
            $pluginPath = 'plugins' . DS . Inflector::underscore($this->plugin) . DS;
            $path = APP . $pluginPath . 'tests' . DS . 'fixtures' . DS;
        }
        $filename = Inflector::underscore($model) . '_fixture.php';
        $header = '$Id';
        $content = "<?php \n/* SVN FILE: {$header}\$ */\n/* " . $model . " Fixture generated on: " . date('Y-m-d H:m:s') . " : " . time() . "*/\n{$out}?>";
        $this->out("\nBaking test fixture for {$model}...");
        if ($this->createFile($path . $filename, $content)) {
            return $records;
        }
        return false;
    }
Пример #18
0
 /**
  * Generates a string representation of a schema.
  *
  * @param array $tableInfo Table schema array
  * @return string fields definitions
  */
 protected function _generateSchema($tableInfo)
 {
     $schema = $this->_Schema->generateTable('f', $tableInfo);
     return substr($schema, 10, -2);
 }
Пример #19
0
    /**
     * testCakeSchema method
     *
     * Test that schema generated postgresql queries are valid. ref #5696
     * Check that the create statement for a schema generated table is the same as the original sql
     *
     * @return void
     * @access public
     */
    function testCakeSchema()
    {
        $db1 =& ConnectionManager::getDataSource('test_suite');
        $db1->cacheSources = false;
        $db1->reconnect(array('persistent' => false));
        $db1->query('CREATE TABLE ' . $db1->fullTableName('datatypes') . ' (
			id serial NOT NULL,
			"varchar" character varying(40) NOT NULL,
			"timestamp" timestamp without time zone,
			date date,
			CONSTRAINT test_suite_data_types_pkey PRIMARY KEY (id)
		)');
        $model =& ClassRegistry::init('datatypes');
        $schema = new CakeSchema(array('connection' => 'test_suite'));
        $result = $schema->read(array('connection' => 'test_suite'));
        $schema->tables = $result['tables']['missing'];
        $result = $db1->createSchema($schema, 'datatypes');
        $this->assertNoPattern('/timestamp DEFAULT/', $result);
        $this->assertPattern('/timestamp\\s*,/', $result);
        $db1->query('DROP TABLE ' . $db1->fullTableName('datatypes'));
        $db1->query($result);
        $result2 = $schema->read(array('connection' => 'test_suite'));
        $schema->tables = $result2['tables']['missing'];
        $result2 = $db1->createSchema($schema, 'datatypes');
        $this->assertEqual($result, $result2);
        $db1->query('DROP TABLE ' . $db1->fullTableName('datatypes'));
    }
Пример #20
0
 /**
  * Test the alter index capabilities of postgres
  *
  * @access public
  * @return void
  */
 function testAlterIndexes()
 {
     $this->db->cacheSources = false;
     $schema1 = new CakeSchema(array('name' => 'AlterTest1', 'connection' => 'test_suite', 'altertest' => array('id' => array('type' => 'integer', 'null' => false, 'default' => 0), 'name' => array('type' => 'string', 'null' => false, 'length' => 50), 'group1' => array('type' => 'integer', 'null' => true), 'group2' => array('type' => 'integer', 'null' => true))));
     $this->db->query($this->db->createSchema($schema1));
     $schema2 = new CakeSchema(array('name' => 'AlterTest2', 'connection' => 'test_suite', 'altertest' => array('id' => array('type' => 'integer', 'null' => false, 'default' => 0), 'name' => array('type' => 'string', 'null' => false, 'length' => 50), 'group1' => array('type' => 'integer', 'null' => true), 'group2' => array('type' => 'integer', 'null' => true), 'indexes' => array('name_idx' => array('column' => 'name', 'unique' => 0), 'group_idx' => array('column' => 'group1', 'unique' => 0), 'compound_idx' => array('column' => array('group1', 'group2'), 'unique' => 0), 'PRIMARY' => array('column' => 'id', 'unique' => 1)))));
     $this->db->query($this->db->alterSchema($schema2->compare($schema1)));
     $indexes = $this->db->index('altertest');
     $this->assertEqual($schema2->tables['altertest']['indexes'], $indexes);
     // Change three indexes, delete one and add another one
     $schema3 = new CakeSchema(array('name' => 'AlterTest3', 'connection' => 'test_suite', 'altertest' => array('id' => array('type' => 'integer', 'null' => false, 'default' => 0), 'name' => array('type' => 'string', 'null' => false, 'length' => 50), 'group1' => array('type' => 'integer', 'null' => true), 'group2' => array('type' => 'integer', 'null' => true), 'indexes' => array('name_idx' => array('column' => 'name', 'unique' => 1), 'group_idx' => array('column' => 'group2', 'unique' => 0), 'compound_idx' => array('column' => array('group2', 'group1'), 'unique' => 0), 'another_idx' => array('column' => array('group1', 'name'), 'unique' => 0)))));
     $this->db->query($this->db->alterSchema($schema3->compare($schema2)));
     $indexes = $this->db->index('altertest');
     $this->assertEqual($schema3->tables['altertest']['indexes'], $indexes);
     // Compare us to ourself.
     $this->assertEqual($schema3->compare($schema3), array());
     // Drop the indexes
     $this->db->query($this->db->alterSchema($schema1->compare($schema3)));
     $indexes = $this->db->index('altertest');
     $this->assertEqual(array(), $indexes);
     $this->db->query($this->db->dropSchema($schema1));
 }
Пример #21
0
 /**
  * Generates a string representation of a schema.
  *
  * @param array $tableInfo Table schema array
  * @return string fields definitions
  */
 protected function _generateSchema($tableInfo)
 {
     $schema = trim($this->_Schema->generateTable('f', $tableInfo), "\n");
     return substr($schema, 13, -1);
 }
Пример #22
0
 /**
  * Adds the DECIMAL column type as a recognized datatype
  *
  * @return void
  */
 function __construct()
 {
     $db =& ConnectionManager::getDataSource('default');
     $db->columns['decimal'] = array('name' => 'decimal', 'formatter' => 'floatval');
     return parent::__construct();
 }