/** * Update database with Schema object * Should be called via the run method * * @param CakeSchema $Schema * @param string $table * @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) { $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(__d('cake_console', 'Schema is up to date.')); $this->_stop(); } $this->out("\n" . __d('cake_console', 'The following statements will run.')); $this->out(array_map('trim', $contents)); if ('y' == $this->in(__d('cake_console', 'Are you sure you want to alter the tables?'), array('y', 'n'), 'n')) { $this->out(); $this->out(__d('cake_console', 'Updating Database...')); $this->_run($contents, 'update', $Schema); } $this->out(__d('cake_console', 'End update.')); }
/** * Assembles and writes a Fixture file * * @param string $model Name of model to bake. * @param string $useTable Name of table to use. * @param array $importOptions Options for public $import * @return string Baked fixture content */ public function bake($model, $useTable = false, $importOptions = array()) { App::uses('CakeSchema', 'Model'); $table = $schema = $records = $import = $modelImport = null; $importBits = array(); if (!$useTable) { $useTable = Inflector::tableize($model); } elseif ($useTable != Inflector::tableize($model)) { $table = $useTable; } if (!empty($importOptions)) { if (isset($importOptions['schema'])) { $modelImport = true; $importBits[] = "'model' => '{$importOptions['schema']}'"; } if (isset($importOptions['records'])) { $importBits[] = "'records' => true"; } if ($this->connection !== 'default') { $importBits[] .= "'connection' => '{$this->connection}'"; } if (!empty($importBits)) { $import = sprintf("array(%s)", implode(', ', $importBits)); } } $this->_Schema = new CakeSchema(); $data = $this->_Schema->read(array('models' => false, 'connection' => $this->connection)); if (!isset($data['tables'][$useTable])) { $this->err('Could not find your selected table ' . $useTable); return false; } $tableInfo = $data['tables'][$useTable]; if (is_null($modelImport)) { $schema = $this->_generateSchema($tableInfo); } if (empty($importOptions['records']) && !isset($importOptions['fromTable'])) { $recordCount = 1; if (isset($this->params['count'])) { $recordCount = $this->params['count']; } $records = $this->_makeRecordString($this->_generateRecords($tableInfo, $recordCount)); } if (!empty($this->params['records']) || isset($importOptions['fromTable'])) { $records = $this->_makeRecordString($this->_getRecordsFromTable($model, $useTable)); } $out = $this->generateFixtureFile($model, compact('records', 'table', 'schema', 'import')); return $out; }
/** * 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; }
/** * 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 */ public function testCakeSchema() { $db1 = ConnectionManager::getDataSource('test'); $db1->cacheSources = false; $db1->rawQuery('CREATE TABLE ' . $db1->fullTableName('datatype_tests') . ' ( id serial NOT NULL, "varchar" character varying(40) NOT NULL, "full_length" character varying NOT NULL, "huge_int" bigint NOT NULL, "timestamp" timestamp without time zone, "date" date, CONSTRAINT test_data_types_pkey PRIMARY KEY (id) )'); $schema = new CakeSchema(array('connection' => 'test')); $result = $schema->read(array('connection' => 'test', 'models' => array('DatatypeTest'))); $schema->tables = array('datatype_tests' => $result['tables']['missing']['datatype_tests']); $result = $db1->createSchema($schema, 'datatype_tests'); $this->assertNotRegExp('/timestamp DEFAULT/', $result); $this->assertRegExp('/\\"full_length\\"\\s*text\\s.*,/', $result); $this->assertContains('timestamp ,', $result); $this->assertContains('"huge_int" bigint NOT NULL,', $result); $db1->query('DROP TABLE ' . $db1->fullTableName('datatype_tests')); $db1->query($result); $result2 = $schema->read(array('connection' => 'test', 'models' => array('DatatypeTest'))); $schema->tables = array('datatype_tests' => $result2['tables']['missing']['datatype_tests']); $result2 = $db1->createSchema($schema, 'datatype_tests'); $this->assertEquals($result, $result2); $db1->query('DROP TABLE ' . $db1->fullTableName('datatype_tests')); }
/** * 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')); }
/** * 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; }
/** * 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; }
/** * testCakeSchemaBegserial method * * Test that schema generated postgresql queries are valid. * * @return void */ public function testCakeSchemaBigserial() { $db1 = ConnectionManager::getDataSource('test'); $db1->cacheSources = false; $db1->rawQuery('CREATE TABLE ' . $db1->fullTableName('bigserial_tests') . ' ( "id" bigserial NOT NULL, "varchar" character varying(40) NOT NULL, PRIMARY KEY ("id") )'); $schema = new CakeSchema(array('connection' => 'test')); $result = $schema->read(array('connection' => 'test', 'models' => array('BigserialTest'))); $schema->tables = array('bigserial_tests' => $result['tables']['missing']['bigserial_tests']); $result = $db1->createSchema($schema, 'bigserial_tests'); $this->assertContains('"id" bigserial NOT NULL,', $result); $db1->query('DROP TABLE ' . $db1->fullTableName('bigserial_tests')); }
/** * test reading schema from plugins. * * @return void */ public function testSchemaReadWithPlugins() { App::objects('model', null, false); App::build(array('Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS))); CakePlugin::load('TestPlugin'); $Schema = new CakeSchema(); $Schema->plugin = 'TestPlugin'; $read = $Schema->read(array('connection' => 'test', 'name' => 'TestApp', 'models' => true)); unset($read['tables']['missing']); $this->assertTrue(isset($read['tables']['auth_users'])); $this->assertTrue(isset($read['tables']['authors'])); $this->assertTrue(isset($read['tables']['test_plugin_comments'])); $this->assertTrue(isset($read['tables']['posts'])); $this->assertTrue(count($read['tables']) >= 4); App::build(); }
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; }
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; }
/** * 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_'); } } } }