/** * @param null $options * @param bool $autoLoad */ public function __construct($options = null, $autoLoad = true) { $this->_db = Zend_Db_Table::getDefaultAdapter(); $this->_options = $options; if (isset($options['blacklist']) && !isset($options['whitelist'])) { if (is_array($options['blacklist'])) { $this->_blackList = $options['blacklist']; } else { $this->_blackList[] = (string) $options['blacklist']; } } elseif (isset($options['whitelist']) && !empty($options['whitelist'])) { if (is_array($options['whitelist'])) { $this->_whiteList = $options['whitelist']; } else { $this->_whiteList[] = (string) $options['whitelist']; } } if ($autoLoad) { $tables = $this->_db->listTables(); foreach ($tables as $table) { $scheme = $this->_db->describeTable($table); $this->addTable($table, $scheme); } } }
/** * Get Table information * * @param string $tableName * @return array */ protected function getTableDescription($tableName) { if (!isset($this->_tableMetadata[$tableName])) { $this->_tableMetadata[$tableName] = $this->_connection->describeTable($tableName); } return $this->_tableMetadata[$tableName]; }
/** * Initializes metadata. * * If metadata cannot be loaded from cache, adapter's describeTable() method is called to discover metadata * information. Returns true if and only if the metadata are loaded from cache. * * @return boolean * @throws Kwf_Exception */ protected function _setupMetadata() { if (count($this->_metadata) > 0) { return true; } // Assume that metadata will be loaded from cache $isMetadataFromCache = true; // Define the cache identifier where the metadata are saved //get db configuration $dbConfig = $this->_db->getConfig(); $port = isset($dbConfig['options']['port']) ? ':' . $dbConfig['options']['port'] : (isset($dbConfig['port']) ? ':' . $dbConfig['port'] : null); $host = isset($dbConfig['options']['host']) ? ':' . $dbConfig['options']['host'] : (isset($dbConfig['host']) ? ':' . $dbConfig['host'] : null); // Define the cache identifier where the metadata are saved $cacheId = 'dbtbl_' . md5($port . $host . '/' . $dbConfig['dbname'] . ':' . $this->_schema . '.' . $this->_name); // If $this has no metadata cache or metadata cache misses if (!($metadata = Kwf_Cache_SimpleStatic::fetch($cacheId))) { // Metadata are not loaded from cache $isMetadataFromCache = false; // Fetch metadata from the adapter's describeTable() method $metadata = $this->_db->describeTable($this->_name, $this->_schema); // If $this has a metadata cache, then cache the metadata Kwf_Cache_SimpleStatic::add($cacheId, $metadata); } // Assign the metadata to $this $this->_metadata = $metadata; // Return whether the metadata were loaded from cache return $isMetadataFromCache; }
/** * Test Adapter's describeTable() method. * Retrieve the adapter's description of the test table and examine it. */ public function testDescribeTable() { $idKey = $this->getResultSetKey('id'); $bodyKey = $this->getResultSetKey('body'); $table = $this->getIdentifier(self::TABLE_NAME); $desc = $this->_db->describeTable($table); $this->assertThat($desc, $this->arrayHasKey($bodyKey)); $this->assertThat($desc[$bodyKey], $this->arrayHasKey('SCHEMA_NAME')); $this->assertThat($desc[$bodyKey], $this->arrayHasKey('TABLE_NAME')); $this->assertThat($desc[$bodyKey], $this->arrayHasKey('COLUMN_NAME')); $this->assertThat($desc[$bodyKey], $this->arrayHasKey('COLUMN_POSITION')); $this->assertThat($desc[$bodyKey], $this->arrayHasKey('DATA_TYPE')); $this->assertThat($desc[$bodyKey], $this->arrayHasKey('DEFAULT')); $this->assertThat($desc[$bodyKey], $this->arrayHasKey('NULLABLE')); $this->assertThat($desc[$bodyKey], $this->arrayHasKey('LENGTH')); $this->assertThat($desc[$bodyKey], $this->arrayHasKey('SCALE')); $this->assertThat($desc[$bodyKey], $this->arrayHasKey('PRECISION')); $this->assertThat($desc[$bodyKey], $this->arrayHasKey('UNSIGNED')); $this->assertThat($desc[$bodyKey], $this->arrayHasKey('PRIMARY')); $this->assertThat($desc[$bodyKey], $this->arrayHasKey('PRIMARY_POSITION')); $this->assertEquals($table, $desc[$bodyKey]['TABLE_NAME']); $this->assertEquals($bodyKey, $desc[$bodyKey]['COLUMN_NAME']); $this->assertEquals(4, $desc[$bodyKey]['COLUMN_POSITION']); $this->assertEquals($this->_textDataType, $desc[$bodyKey]['DATA_TYPE']); $this->assertEquals('', $desc[$bodyKey]['DEFAULT']); $this->assertTrue($desc[$bodyKey]['NULLABLE']); $this->assertEquals(0, $desc[$bodyKey]['SCALE']); $this->assertEquals(0, $desc[$bodyKey]['PRECISION']); $this->assertEquals('', $desc[$bodyKey]['PRIMARY']); $this->assertEquals('', $desc[$bodyKey]['PRIMARY_POSITION']); $this->assertTrue($desc[$idKey]['PRIMARY']); $this->assertEquals(1, $desc[$idKey]['PRIMARY_POSITION']); }
/** * Populate static properties for this table module. * * @return void * @throws Zend_Db_Table_Exception */ protected function _setup() { // get the database adapter if (!$this->_db) { $this->_db = self::getDefaultAdapter(); } if (!$this->_db instanceof Zend_Db_Adapter_Abstract) { require_once 'Zend/Db/Table/Exception.php'; throw new Zend_Db_Table_Exception('No object of type Zend_Db_Adapter_Abstract has been specified'); } // get the table name if (!$this->_name) { require_once 'Zend/Db/Table/Exception.php'; throw new Zend_Db_Table_Exception('No table name has been specified'); } // get the table columns if (!$this->_cols) { $desc = $this->_db->describeTable($this->_name); $this->_cols = array_keys($desc); } // primary key if ($this->_primary && array_intersect((array) $this->_primary, $this->_cols) !== (array) $this->_primary) { require_once 'Zend/Db/Table/Exception.php'; throw new Zend_Db_Table_Exception("Primary key column(s) (" . implode(',', (array) $this->_primary) . ") are not columns in this table (" . implode(',', $this->_cols) . ")"); } }
/** * the constructor */ public function __construct() { $this->_db = Tinebase_Core::getDb(); $this->groupsTable = new Tinebase_Db_Table(array('name' => SQL_TABLE_PREFIX . $this->_tableName)); $this->groupMembersTable = new Tinebase_Db_Table(array('name' => SQL_TABLE_PREFIX . 'group_members')); try { // MySQL throws an exception if the table does not exist // PostgreSQL returns an empty array if the table does not exist $tableDescription = $this->_db->describeTable(SQL_TABLE_PREFIX . 'addressbook'); if (!empty($tableDescription)) { $this->_addressBookInstalled = true; } } catch (Zend_Db_Statement_Exception $zdse) { // nothing to do } }
/** * checks if a given table exists * * @param string $_tableSchema * @param string $_tableName * @return boolean return true if the table exists, otherwise false */ public function tableExists($_tableName) { $tableName = SQL_TABLE_PREFIX . $_tableName; try { $tableInfo = $this->_db->describeTable($tableName); } catch (Zend_Db_Statement_Exception $e) { $tableInfo = null; } return !empty($tableInfo); }
/** * Get the primary key name through table metadata * @param full table name $table */ protected function _getPrimaryKey($table) { $metadata = $this->_db->describeTable($table); $primaryKey = NULL; foreach ($metadata as $field => $description) { if ($description["PRIMARY"]) { $primaryKey = $field; break; } } return $primaryKey; }
/** * * @param array $enumValues * @param boolean $reverse */ protected function _alterEnumValues(array $enumValues, $reverse = false) { foreach ($enumValues as $tableName => $fields) { if ($this->_isTableExists($tableName)) { $table = $this->_db->describeTable($tableName); foreach ($fields as $fieldName => $fieldEnums) { if (!isset($table[$fieldName])) { continue; } preg_match('/^enum\\((.*)\\)$/', $table[$fieldName]['DATA_TYPE'], $matches); foreach (explode(',', $matches[1]) as $value) { $enums[] = trim($value, "'"); } $newEnums = $enums; if (isset($fieldEnums['add'])) { if (!$reverse) { foreach ($fieldEnums['add'] as $fieldEnum) { $newEnums[] = $fieldEnum; } } else { foreach ($fieldEnums['add'] as $fieldEnum) { $this->_db->delete($tableName, $fieldName . ' = \'' . $fieldEnum . '\''); } $newEnums = array_diff($newEnums, $fieldEnums['add']); } $newEnums = array_unique($newEnums); } if (isset($fieldEnums['remove'])) { if (!$reverse) { foreach ($fieldEnums['remove'] as $fieldEnum) { $this->_db->delete($tableName, $fieldName . ' = \'' . $fieldEnum . '\''); } $newEnums = array_diff($newEnums, $fieldEnums['remove']); } else { foreach ($fieldEnums['remove'] as $fieldEnum) { $newEnums[] = $fieldEnum; } } $newEnums = array_unique($newEnums); } sort($enums); sort($newEnums); if ($enums != $newEnums) { foreach ($newEnums as &$value) { $value = '\'' . $value . '\''; } $table[$fieldName]['DATA_TYPE'] = 'enum(' . implode(',', $newEnums) . ')'; $this->_alterTable($table[$fieldName]); } } } } }
/** * Find PRIMARY KEY * @param Zend_Db_Adapter_Abstract $db * @param string $table * @return array | boolean (false) */ public function findPrimaryKey(Zend_Db_Adapter_Abstract $db, $table) { $fields = $db->describeTable($table); $primary = false; foreach ($fields as $name => $info) { if ($info['PRIMARY'] == 1) { $primary = $info; break; } } return $primary; }
/** * Is the schema ready? * * @return bool */ public function hasSchema() { try { $schema = $this->adapter->describeTable($this->tableName); } catch (\Zend_Db_Statement_Exception $exception) { return false; } catch (\PDOException $exception) { return false; } if (is_array($schema) && !empty($schema)) { return true; } return false; }
/** * * @param string $table * @param string $adapter * @param string $module * @return void * @throws Zend_Tool_Project_Exception * @throws Exception */ public function create($table, $adapter, $module = null) { $name = ZendT_Tool_ModelTProvider::convertTableNameToClassName($table); $this->_print(' Criando Models '); $this->_print('name: ' . $name . ' | table: ' . $table . ' | adapter : ' . $adapter . ' | module: ' . $module); $this->_loadProfile(self::NO_PROFILE_THROW_EXCEPTION); $this->connect($this->_loadedProfile, $adapter); // Check that there is not a dash or underscore, return if doesnt match regex if (preg_match('#[_-]#', $name)) { throw new Zend_Tool_Project_Provider_Exception('Form names should be camel cased.'); } $originalName = $name; $name = ucfirst($name); if ($table == '') { throw new Zend_Tool_Project_Provider_Exception('You must provide both the Form name as well as the actual db table\'s name.'); } // get request/response object $request = $this->_registry->getRequest(); $response = $this->_registry->getResponse(); // alert the user about inline converted names $tense = $request->isPretend() ? 'would be' : 'is'; if ($name !== $originalName) { $response->appendContent('Note: The canonical model name that ' . $tense . ' used with other providers is "' . $name . '";' . ' not "' . $originalName . '" as supplied', array('color' => array('yellow'))); } /** * Cria o DB Table */ try { $formResources = Zend_Tool_Project_Provider_Form::createResource($this->_loadedProfile, $name, $module); } catch (Exception $e) { $response = $this->_registry->getResponse(); $response->setException($e); return; } // do the creation if ($request->isPretend()) { $response->appendContent('Would create a Form at ' . $formResources->getContext()->getPath()); } else { $response->appendContent('Creating a Form at ' . $formResources->getContext()->getPath()); $formResources->create(); $this->_storeProfile(); $fileName = $formResources->getContext()->getPath(); $formContext = new ZendT_Tool_Context_FormFile(); $descTable = $this->_dbAdapter->describeTable($originalName); $formContext->setProperties($descTable); file_put_contents($fileName, "<?php \n" . $formContext->getContents() . "\n?>"); } $this->_print(' Finalizado Models '); }
/** * Initialize metadata. * Call describeTable() to discover metadata information. * * @return void * @throws Zend_Db_Table_Exception */ protected function _setupMetadata() { // @todo: support for caching the information from describeTable. if (strpos($this->_name, '.')) { list($schemaName, $tableName) = explode('.', $this->_name); $this->_schema = $schemaName; $this->_name = $tableName; } else { $schemaName = $this->_schema; $tableName = $this->_name; } $this->_metadata = $this->_db->describeTable($tableName, $schemaName); if (!$this->_cols) { $this->_cols = array_keys($this->_metadata); } }
/** * Initializes metadata. * * If metadata cannot be loaded from cache, adapter's describeTable() method is called to discover metadata * information. Returns true if and only if the metadata are loaded from cache. * * @return boolean * @throws Zend_Db_Table_Exception */ protected function _setupMetadata() { if (strpos($this->_name, '.')) { list($schemaName, $tableName) = explode('.', $this->_name); $this->_schema = $schemaName; $this->_name = $tableName; } else { $schemaName = $this->_schema; $tableName = $this->_name; } // Assume that metadata will be loaded from cache $isMetadataFromCache = true; // If $this has no metadata cache but the class has a default metadata cache if (null === $this->_metadataCache && null !== self::$_defaultMetadataCache) { // Make $this use the default metadata cache of the class $this->_setMetadataCache(self::$_defaultMetadataCache); } // If $this has a metadata cache if (null !== $this->_metadataCache) { // Define the cache identifier where the metadata are saved $cacheId = md5("{$schemaName}.{$tableName}"); } // If $this has no metadata cache or metadata cache misses if (null === $this->_metadataCache || !($metadata = $this->_metadataCache->load($cacheId))) { // Metadata are not loaded from cache $isMetadataFromCache = false; // Fetch metadata from the adapter's describeTable() method $metadata = $this->_db->describeTable($tableName, $schemaName); // If $this has a metadata cache, then cache the metadata if (null !== $this->_metadataCache && !$this->_metadataCache->save($metadata, $cacheId)) { /** * @see Zend_Db_Table_Exception */ require_once 'Zend/Db/Table/Exception.php'; throw new Zend_Db_Table_Exception('Failed saving metadata to metadataCache'); } } // Assign the metadata to $this $this->_metadata = $metadata; // Update the columns $this->_cols = array_keys($this->_metadata); // Return whether the metadata were loaded from cache return $isMetadataFromCache; }
public static function loadSchemaFromDb(Zend_Db_Adapter_Abstract $db, Zend_Cache_Core $cache) { static $tables = array(); if (empty($tables)) { if (!($tables = $cache->load('tables'))) { $tables = $db->listTables(); $cache->save($tables, 'tables'); } } foreach ($tables as $table) { if (!isset(self::$schema[$table])) { if (!($tableStructure = $cache->load('tables_' . $table))) { $tableStructure = $db->describeTable($table); $cache->save($tableStructure, 'tables_' . $table); } self::$schema[$table] = $tableStructure; } } }
/** * Populate static properties for this table module. * * @return void * @throws Zend_Db_Table_Exception */ protected function _setup($config = array()) { // get the database adapter if (!$this->_db) { $this->_db = $this->_getDefaultAdapter(); } if (!$this->_db instanceof Zend_Db_Adapter_Abstract) { throw new Zend_Db_Table_Exception('db object does not extend Zend_Db_Adapter_Abstract'); } // get the table name if (isset($config['name'])) { $this->_name = $config['name']; } if (!$this->_name) { $this->_name = self::$_inflector->underscore(get_class($this)); } // get the table columns if (!$this->_cols) { $tmp = array_keys($this->_db->describeTable($this->_name)); foreach ($tmp as $native) { $this->_cols[$native] = self::$_inflector->camelize($native); } } // primary key if (isset($config['primary'])) { $this->_primary = $config['primary']; } if (!$this->_primary) { // none specified $table = $this->_name; throw new Zend_Db_Table_Exception("primary key not specified for table '{$table}'"); } if (!array_key_exists($this->_primary, $this->_cols)) { // wrong name $key = $this->_primary; $table = $this->_name; throw new Zend_Db_Table_Exception("primary key '{$key}' not in columns for table '{$table}'"); } }
/** * * @param string $table * @param string $adapter * @param string $module * @return void * @throws Zend_Tool_Project_Exception * @throws Exception */ public function create($table, $adapter, $module = null) { $name = ZendT_Tool_ModelTProvider::convertTableNameToClassName($table); $this->_print(' Criando Models '); $this->_print('name: ' . $name . ' | table: ' . $table . ' | adapter : ' . $adapter . ' | module: ' . $module); $this->_loadProfile(self::NO_PROFILE_THROW_EXCEPTION); $applicationConfigResource = $this->_loadedProfile->search('ApplicationConfigFile'); if (!$applicationConfigResource) { throw new Zend_Tool_Project_Exception('A project with an application config file is required to use this provider.'); } $zf = $applicationConfigResource->getAsZendConfig(); $_configDb = $zf->resources->multidb->{$adapter}; if (!$_configDb) { throw new Zend_Tool_Project_Exception('Adapter not found in config application "resources.multidb.' . $adapter . '" .'); } $configDb = array(); $configDb['host'] = $_configDb->host; $configDb['username'] = $_configDb->username; $configDb['password'] = $_configDb->password; $configDb['dbname'] = $_configDb->dbname; $this->_dbAdapter = Zend_Db::factory($_configDb->adapter, $configDb); $sql = "SELECT uccfk.column_name\n ,uccpk.table_name table_name_pk\n ,NULL object_name_pk\n ,uccpk.column_name column_name_pk\n FROM user_cons_columns uccfk\n ,user_constraints uc\n ,user_cons_columns uccpk\n WHERE uccfk.constraint_name = uc.constraint_name\n AND uc.r_constraint_name = uccpk.constraint_name\n AND uc.constraint_type = 'R'\n AND uccfk.table_name = '" . strtoupper($table) . "'"; $referenceMap = $this->_dbAdapter->fetchAll($sql); foreach ($referenceMap as &$reference) { $reference['OBJECT_NAME_PK'] = $this->getObjectName($reference['TABLE_NAME_PK']); } $sql = "SELECT distinct uccfk.TABLE_NAME\n FROM user_cons_columns uccfk\n ,user_constraints uc\n ,user_cons_columns uccpk\n WHERE uccfk.constraint_name = uc.constraint_name\n AND uc.r_constraint_name = uccpk.constraint_name\n AND uc.constraint_type = 'R'\n AND uccpk.table_name = '" . strtoupper($table) . "'"; $dependentTables = $this->_dbAdapter->fetchAll($sql); foreach ($dependentTables as &$dependentTable) { $dependentTable['OBJECT_NAME'] = $this->getObjectName($dependentTable['TABLE_NAME']); } // Check that there is not a dash or underscore, return if doesnt match regex if (preg_match('#[_-]#', $name)) { throw new Zend_Tool_Project_Provider_Exception('DbTable names should be camel cased.'); } $originalName = $name; $name = ucfirst($name); if ($table == '') { throw new Zend_Tool_Project_Provider_Exception('You must provide both the DbTable name as well as the actual db table\'s name.'); } /*if (Zend_Tool_Project_Provider_DbTable::hasResource($this->_loadedProfile, $name, $module)) { throw new Zend_Tool_Project_Provider_Exception('This project already has a DbTable named ' . $name); }*/ // get request/response object $request = $this->_registry->getRequest(); $response = $this->_registry->getResponse(); // alert the user about inline converted names $tense = $request->isPretend() ? 'would be' : 'is'; if ($name !== $originalName) { $response->appendContent('Note: The canonical model name that ' . $tense . ' used with other providers is "' . $name . '";' . ' not "' . $originalName . '" as supplied', array('color' => array('yellow'))); } /** * Cria o DB Table */ try { $tableResource = Zend_Tool_Project_Provider_DbTable::createResource($this->_loadedProfile, $name, $table, $module); } catch (Exception $e) { $response = $this->_registry->getResponse(); $response->setException($e); return; } // do the creation if ($request->isPretend()) { $response->appendContent('Would create a DbTable at ' . $tableResource->getContext()->getPath()); } else { $response->appendContent('Creating a DbTable at ' . $tableResource->getContext()->getPath()); $tableResource->create(); $this->_storeProfile(); $fileName = $tableResource->getContext()->getPath(); $dbTableContext = new ZendT_Tool_Context_DbTableModelFile(); $this->_dbAdapter->describeTable($originalName); $data = array(); $data['modelName'] = $name; $data['moduleName'] = $module; $data['tableName'] = $table; $data['adapter'] = $adapter; $data['referenceMap'] = $referenceMap; $data['dependentTables'] = $dependentTables; $dbTableContext->setProperties($data); file_put_contents($fileName, "<?php \n" . $dbTableContext->getContents() . "\n?>"); /** * Configura o nome do objeto dentro dos comentários * da tabela */ $this->setObjectName($table, ZendT_Tool_ModelTProvider::convertTableNameToObjectName($module, $table)); } /** * Cria o Model */ try { $modelResource = Zend_Tool_Project_Provider_Model::createResource($this->_loadedProfile, $name, $module); } catch (Exception $e) { $response->setException($e); return; } // do the creation if ($request->isPretend()) { $response->appendContent('Would create a model at ' . $modelResource->getContext()->getPath()); } else { $response->appendContent('Creating a model at ' . $modelResource->getContext()->getPath()); $modelResource->create(); $this->_storeProfile(); $fileName = $modelResource->getContext()->getPath(); $modelContext = new ZendT_Tool_Context_ModelFile(); $data = array(); $data['modelName'] = $name; $data['moduleName'] = $module; $modelContext->setProperties($data); file_put_contents($fileName, "<?php \n" . $modelContext->getContents() . "\n?>"); } $this->_print(' Finalizado Models '); }
/** * * @param string $table * @param string $adapter * @param string $module * @return void * @throws Zend_Tool_Project_Exception * @throws Exception */ public function config($table, $adapter, $module = null, $name = null, $env = null, $schema = null) { if (!$schema) { $schema = $adapter; } $this->_print(' Criando arquivo de configuracao '); $this->_print(' table: ' . $table . ' | adapter : ' . $adapter . ' | module: ' . $module); $this->_loadProfile(self::NO_PROFILE_THROW_EXCEPTION); $table = strtolower($table); $module = strtolower($module); if ($name !== null) { $controllerName = strtolower(str_replace('_', '-', $name)); } else { $controllerName = strtolower(str_replace('_', '-', $table)); } $path = $this->_loadedProfile->getAttribute('projectDirectory'); $this->_configModule($path, $module); $dirModules = $path . '/application/configs/modules'; if (!is_dir($dirModules)) { mkdir($dirModules); } $dirModule = $dirModules . '/' . $module; if (!is_dir($dirModule)) { mkdir($dirModule); } $fileName = $dirModule . '/' . $table . '.php'; /** * */ $config = array(); if (!file_exists($fileName)) { $config['table']['name'] = $table; if ($name != null || $name) { $config['table']['modelName'] = $name; } else { $config['table']['modelName'] = $table; } $config['table']['schema'] = $adapter; $config['table']['sequenceName'] = 'sid_' . $table; $config['table']['moduleName'] = $module; $config['table']['objectName'] = str_replace("_Crud", "", ZendT_Lib::convertTableNameToObjectName($module, $config['table']['modelName'])); $config['table']['controllerName'] = str_replace("Model_", "", $config['table']['objectName']) || 'Controller'; $config['table']['seeker']['field']['search'] = ''; $config['table']['seeker']['field']['display'] = ''; $config['table']['seeker']['search']['css-width'] = '270px'; $config['table']['seeker']['display']['css-width'] = '0px'; $config['table']['seeker']['url']['grid'] = "/{$module}/{$controllerName}/grid"; $config['table']['seeker']['url']['search'] = "/{$module}/{$controllerName}/seeker-search"; $config['table']['seeker']['url']['retrieve'] = "/{$module}/{$controllerName}/retrieve"; $config['table']['seeker']['modal']['width'] = 800; $config['table']['seeker']['modal']['height'] = 450; } else { $config = (require $fileName); } $config['table']['seeker']['field']['id'] = array(); $this->_connect($this->_loadedProfile, $adapter, $env); $describeModel = $this->_dbAdapter->describeTable($table, $schema); if (count($describeModel) <= 0) { $this->_print('Erro ao localizar as colunas da Tabela, certifique a conexao e nome da tabela'); exit; } else { /** * */ /* if (!isset($config['table']['columns'])) { $config['table']['columns'] = array(); } */ /** * Força para manter a ordem das colunas */ foreach ($describeModel as $columnName => $column) { if (!isset($config['table']['columns'][$columnName])) { if (!$config['table']['columns'][strtolower($columnName)]['label']) { $config['table']['columns'][strtolower($columnName)]['label'] = $columnName; } } } } //print_r($describeModel); //$describeModel['PRECISION'] = (int) $describeModel['PRECISION']; if (!isset($config['table']['dependentTables'])) { $config['table']['dependentTables'] = array(); } if (!isset($config['table']['referenceMaps'])) { $config['table']['referenceMaps'] = array(); } if (isset($describeModel['REFERENCE_MAP'])) { $_referenceMaps = array(); foreach ($describeModel['REFERENCE_MAP'] as &$reference) { $modelName = ZendT_Tool_Crud::getModelName($this->_loadedProfile->getAttribute('projectDirectory'), $reference['TABLE_NAME_REFERENCE'], $reference['SCHEMA_NAME_REFERENCE']); if ($modelName) { $data = array(); $data['columnName'] = $reference['COLUMN_NAME']; $data['objectNameReference'] = $modelName; $data['tableNameReference'] = strtolower($reference['TABLE_NAME_REFERENCE']); $data['schemaNameReference'] = strtolower($reference['SCHEMA_NAME_REFERENCE']); $data['columnReference'] = $reference['COLUMN_NAME_REFERENCE']; $_referenceMaps[] = $data; } else { $data = array(); $data['columnName'] = $reference['COLUMN_NAME']; if (strtolower($reference['TABLE_NAME_REFERENCE']) == strtolower($table)) { $data['objectNameReference'] = $config['table']['objectName']; } else { $data['objectNameReference'] = str_replace("_Crud", "", ZendT_Lib::convertTableNameToObjectName($module, $reference['TABLE_NAME_REFERENCE'])); } $data['tableNameReference'] = strtolower($reference['TABLE_NAME_REFERENCE']); $data['schemaNameReference'] = strtolower($reference['SCHEMA_NAME_REFERENCE']); $data['columnReference'] = $reference['COLUMN_NAME_REFERENCE']; $_referenceMaps[] = $data; } $config['table']['columns'][strtolower($reference['COLUMN_NAME'])]['referenceMap'] = true; } $config['table']['referenceMaps'] = $_referenceMaps; } if (isset($describeModel['DEPENDENT_TABLES'])) { $_dependentTables = array(); foreach ($describeModel['DEPENDENT_TABLES'] as &$dependentTable) { $modelName = ZendT_Tool_Crud::getModelName($this->_loadedProfile->getAttribute('projectDirectory'), $dependentTable['TABLE_NAME'], $dependentTable['SCHEMA_NAME'], true); if ($modelName) { $_dependentTables[] = $modelName['table']['objectName']; $tab['description'] = $modelName['table']['description']; $tab['url'] = str_replace('/grid', '/form/grid/1', $modelName['table']['seeker']['url']['grid']); $tab['column'] = strtolower($dependentTable['COLUMN_NAME']); $tab['message'] = 'Necessário seleção ' . $config['table']['description']; if (!isset($config['table']['tabs'][$modelName['table']['name']])) { $config['table']['tabs'][$modelName['table']['name']] = $tab; } } else { $_dependentTables[] = str_replace("_Crud", "", ZendT_Lib::convertTableNameToObjectName($module, $dependentTable['TABLE_NAME'])); /*$tab['description'] = $dependentTable['TABLE_NAME']; $tab['url'] = '/' . strtolower($module).'/' . strtolower(str_replace('_', '-', $dependentTable['TABLE_NAME'])) . '/form/grid/1'; $tab['column'] = 'ID_' . strtoupper($config['table']['name']); $tab['message'] = 'Necessário seleção ' . $config['table']['description'];*/ } } $config['table']['dependentTables'] = $_dependentTables; //$config['table']['tabs'] = $_tabs; } if (!isset($config['table']['form'])) { $config['table']['form']['url']['retrieve'] = "/{$module}/{$controllerName}/retrieve"; $config['table']['form']['url']['insert'] = "/{$module}/{$controllerName}/insert"; $config['table']['form']['url']['update'] = "/{$module}/{$controllerName}/update"; $config['table']['form']['url']['delete'] = "/{$module}/{$controllerName}/delete"; } unset($describeModel['REFERENCE_MAP']); unset($describeModel['DEPENDENT_TABLES']); $primary = array(); foreach ($describeModel as $columnName => $column) { $columnName = strtolower($columnName); if ($column['PRECISION']) { $column['LENGTH'] = (int) $column['PRECISION']; } if ($column['SCALE']) { $column['LENGTH'] -= (int) $column['SCALE']; $column['LENGTH'] .= '.' . $column['SCALE']; } /* if (!isset($config['table']['columns'])) { $config['table']['columns'] = array(); } */ /* if (!isset($config['table']['columns'][$columnName])) { $config['table']['columns'][$columnName] = array(); } */ /* if (!isset($config['table']['columns'][$columnName]['object'])) { $config['table']['columns'][$columnName]['object'] = array(); } */ //$this->_print('Coluna '.$columnName.' => Label: '.$config['table']['columns'][$columnName]['label']); if ($config['table']['columns'][$columnName]['label'] == '') { $config['table']['columns'][$columnName]['label'] = $columnName; } //$this->_print('Coluna '.$columnName.' => Label: '.$config['table']['columns'][$columnName]['label']); #$config['table']['columns'][$columnName]['label'] = $config['table']['columns'][$columnName]['label']; if (!isset($config['table']['columns'][$columnName]['multiple'])) { $config['table']['columns'][$columnName]['multiple'] = 0; } if (!isset($config['table']['columns'][$columnName]['type'])) { $config['table']['columns'][$columnName]['type'] = 'String'; } if (!isset($config['table']['columns'][$columnName]['object']['mask'])) { $config['table']['columns'][$columnName]['object']['mask'] = null; } if (!isset($config['table']['columns'][$columnName]['object']['charMask'])) { $config['table']['columns'][$columnName]['object']['charMask'] = '@'; } if (!isset($config['table']['columns'][$columnName]['object']['filter'])) { $config['table']['columns'][$columnName]['object']['filter'][] = 'trim'; $config['table']['columns'][$columnName]['object']['filter'][] = 'strtoupper'; $config['table']['columns'][$columnName]['object']['filter'][] = 'removeAccent'; } if (!isset($config['table']['columns'][$columnName]['object']['filterDb'])) { $config['table']['columns'][$columnName]['object']['filterDb'][] = ''; } if (!isset($config['table']['columns'][$columnName]['object']['validators'])) { $config['table']['columns'][$columnName]['object']['validators'] = array(); } if (!isset($config['table']['columns'][$columnName]['object']['listOptions'])) { $config['table']['columns'][$columnName]['object']['listOptions'] = array(); } $config['table']['columns'][$columnName]['object']['listOptions'] = $config['table']['columns'][$columnName]['object']['listOptions']; $config['table']['columns'][$columnName]['type'] = $column['DATA_TYPE']; $config['table']['columns'][$columnName]['length'] = $column['LENGTH']; $config['table']['columns'][$columnName]['nullable'] = $column['NULLABLE']; if (!isset($config['table']['primary'])) { $config['table']['primary'] = array(); } $column['DATA_TYPE'] = strtoupper($column['DATA_TYPE']); if ($column['PRIMARY']) { /** * @todo pensar em uma forma de tratar os casos de chave composta */ $config['table']['seeker']['field']['id'] = $columnName; $primary[] = $columnName; $config['table']['columns'][$columnName]['type'] = 'Integer'; $config['table']['columns'][$columnName]['object']['type'] = 'Text'; $config['table']['columns'][$columnName]['object']['text']['css-width'] = $column['LENGTH'] * 8.75; if ($config['table']['columns'][$columnName]['object']['text']['css-width'] > 300) { $config['table']['columns'][$columnName]['object']['text']['css-width'] = '300px'; } else { if ($config['table']['columns'][$columnName]['object']['text']['css-width'] < 100) { $config['table']['columns'][$columnName]['object']['text']['css-width'] = '100px'; } else { $config['table']['columns'][$columnName]['object']['text']['css-width'] .= 'px'; } } $config['table']['columns'][$columnName]['object']['text']['maxlength'] = $column['LENGTH']; $config['table']['columns'][$columnName]['object']['text']['id'] = null; } elseif (isset($config['table']['columns'][$columnName]['referenceMap'])) { //substr(strtolower($columnName),0,2) == 'id' || is_numeric(strpos($columnName, '_id'))) { $config['table']['columns'][$columnName]['type'] = 'Integer'; $config['table']['columns'][$columnName]['object']['type'] = 'Seeker'; $load = false; if (!isset($config['table']['columns'][$columnName]['object']['type'])) { $load = true; } elseif (!in_array($config['table']['columns'][$columnName]['object']['type'], array('Seeker'))) { $load = true; } if (!isset($config['table']['columns'][$columnName]['object']['seeker'])) { $configSeeker = ZendT_Tool_Crud::getConfigSeeker($this->_loadedProfile->getAttribute('projectDirectory'), $config, $columnName); $config['table']['columns'][$columnName]['object']['seeker'] = array(); $config['table']['columns'][$columnName]['object']['seeker'] = $configSeeker; } } elseif (in_array($column['DATA_TYPE'], array('VARCHAR2', 'VARCHAR', 'CHAR'))) { $load = false; if (!isset($config['table']['columns'][$columnName]['object']['type'])) { $load = true; } elseif (!in_array($config['table']['columns'][$columnName]['object']['type'], array('Text', 'Select'))) { $load = true; } if (!isset($config['table']['columns'][$columnName]['object']['type'])) { $config['table']['columns'][$columnName]['object']['type'] = 'Text'; } if (!isset($config['table']['columns'][$columnName]['object']['text'])) { $config['table']['columns'][$columnName]['object']['text'] = array(); } if ($config['table']['seeker']['field']['search'] == '') { $config['table']['seeker']['field']['search'] = $columnName; } $config['table']['columns'][$columnName]['object']['text']['maxlength'] = $column['LENGTH']; $validatorNew = array('name' => 'Zend_Validate_StringLength', 'param' => array('max' => (int) $column['LENGTH'])); foreach ($config['table']['columns'][$columnName]['object']['validators'] as &$validator) { if ($validator['name'] == 'Zend_Validate_StringLength') { $validator = $validatorNew; $validatorNew = null; } } if ($validatorNew !== null) { $config['table']['columns'][$columnName]['object']['validators'][] = $validatorNew; } if ($load) { $config['table']['columns'][$columnName]['object']['text']['css-width'] = $column['LENGTH'] * 8.75; if ($config['table']['columns'][$columnName]['object']['text']['css-width'] > 200) { $config['table']['columns'][$columnName]['object']['text']['css-width'] = '200px'; } else { if ($config['table']['columns'][$columnName]['object']['text']['css-width'] < 100) { $config['table']['columns'][$columnName]['object']['text']['css-width'] = '100px'; } else { $config['table']['columns'][$columnName]['object']['text']['css-width'] .= 'px'; } } $config['table']['columns'][$columnName]['object']['text']['id'] = null; $config['table']['columns'][$columnName]['object']['mask'] = null; } $config['table']['columns'][$columnName]['type'] = 'String'; } elseif (in_array($column['DATA_TYPE'], array('CLOB'))) { $load = false; if (!isset($config['table']['columns'][$columnName]['object']['type'])) { $load = true; } elseif (!in_array($config['table']['columns'][$columnName]['object']['type'], array('Text', 'Select'))) { $load = true; } $config['table']['columns'][$columnName]['object']['type'] = 'Textare'; if (!isset($config['table']['columns'][$columnName]['object']['textare'])) { $config['table']['columns'][$columnName]['object']['textare'] = array(); } if ($load) { $config['table']['columns'][$columnName]['object']['textare']['id'] = null; $config['table']['columns'][$columnName]['object']['textare']['html'] = false; $config['table']['columns'][$columnName]['object']['textare']['cols'] = 50; $config['table']['columns'][$columnName]['object']['textare']['rows'] = 10; } $config['table']['columns'][$columnName]['type'] = 'StringLong'; } elseif (in_array($column['DATA_TYPE'], array('BLOB'))) { $load = false; if (!isset($config['table']['columns'][$columnName]['object']['type'])) { $load = true; } $config['table']['columns'][$columnName]['object']['type'] = 'File'; if ($load) { $config['table']['columns'][$columnName]['object']['file']['id'] = null; } $config['table']['columns'][$columnName]['type'] = 'BinaryLong'; } elseif (in_array($column['DATA_TYPE'], array('DATE'))) { $load = false; if (!isset($config['table']['columns'][$columnName]['object']['type'])) { $load = true; } elseif (!in_array($config['table']['columns'][$columnName]['object']['type'], array('DateTime', 'Date'))) { $load = true; } if ($load) { unset($config['table']['columns'][$columnName]['object'][strtolower($config['table']['columns'][$columnName]['object']['type'])]); if (!isset($config['table']['columns'][$columnName]['object']['date'])) { $config['table']['columns'][$columnName]['object']['date'] = array(); } if (is_numeric(strpos(strtoupper($columnName), 'DH_'))) { $config['table']['columns'][$columnName]['object']['type'] = 'DateTime'; $config['table']['columns'][$columnName]['object']['date']['css-width'] = '87.5px'; $config['table']['columns'][$columnName]['object']['date']['maxlength'] = 10; $config['table']['columns'][$columnName]['object']['time']['css-width'] = '43.75px;'; $config['table']['columns'][$columnName]['object']['time']['maxlength'] = 5; $config['table']['columns'][$columnName]['type'] = 'DateTime'; } else { $config['table']['columns'][$columnName]['object']['type'] = 'Date'; $config['table']['columns'][$columnName]['object']['date']['css-width'] = '87.5px'; $config['table']['columns'][$columnName]['object']['date']['maxlength'] = 10; $config['table']['columns'][$columnName]['object']['date']['id'] = null; $config['table']['columns'][$columnName]['type'] = 'Date'; } } } elseif (in_array($column['DATA_TYPE'], array('DATETIME'))) { $load = false; if (!isset($config['table']['columns'][$columnName]['object']['type'])) { $load = true; } elseif (!in_array($config['table']['columns'][$columnName]['object']['type'], array('DateTime'))) { $load = true; } if ($load) { if (!isset($config['table']['columns'][$columnName]['object']['datetime'])) { $config['table']['columns'][$columnName]['object']['datetime'] = array(); } unset($config['table']['columns'][$columnName]['object'][strtolower($config['table']['columns'][$columnName]['object']['type'])]); $config['table']['columns'][$columnName]['object']['type'] = 'DateTime'; $config['table']['columns'][$columnName]['object']['date']['css-width'] = '87.5px'; $config['table']['columns'][$columnName]['object']['date']['maxlength'] = 10; $config['table']['columns'][$columnName]['object']['date']['id'] = null; $config['table']['columns'][$columnName]['object']['time']['css-width'] = '43.75px'; $config['table']['columns'][$columnName]['object']['time']['maxlength'] = 5; $config['table']['columns'][$columnName]['object']['time']['id'] = null; } $config['table']['columns'][$columnName]['type'] = 'DateTime'; } elseif (in_array($column['DATA_TYPE'], array('TIME'))) { $load = false; if (!isset($config['table']['columns'][$columnName]['object']['type'])) { $load = true; } elseif (!in_array($config['table']['columns'][$columnName]['object']['type'], array('Time'))) { $load = true; } if ($load) { if (!isset($config['table']['columns'][$columnName]['object']['time'])) { $config['table']['columns'][$columnName]['object']['time'] = array(); } unset($config['table']['columns'][$columnName]['object'][strtolower($config['table']['columns'][$columnName]['object']['type'])]); $config['table']['columns'][$columnName]['object']['type'] = 'Time'; $config['table']['columns'][$columnName]['object']['time']['css-width'] = '43.75px'; $config['table']['columns'][$columnName]['object']['time']['maxlength'] = 5; $config['table']['columns'][$columnName]['object']['time']['id'] = null; } $config['table']['columns'][$columnName]['type'] = 'Time'; } elseif (in_array($column['DATA_TYPE'], array('NUMBER', 'INTEGER', 'DECIMAL', 'INT'))) { if (!isset($config['table']['columns'][$columnName]['object']['numeric'])) { $config['table']['columns'][$columnName]['object']['numeric'] = array(); } $config['table']['columns'][$columnName]['object']['type'] = 'Numeric'; $aux = explode('.', $column['LENGTH']); $config['table']['columns'][$columnName]['object']['numeric']['numDecimal'] = $aux[1]; $config['table']['columns'][$columnName]['object']['numeric']['numInteger'] = $aux[0]; $config['table']['columns'][$columnName]['object']['numeric']['id'] = null; unset($aux); $config['table']['columns'][$columnName]['type'] = 'Number'; } if ($column['NULLABLE']) { $config['table']['columns'][$columnName]['object']['required'] = false; } else { $config['table']['columns'][$columnName]['object']['required'] = true; } } if (count($primary) > 0) { $config['table']['primary'] = $primary; } if (count($config['table']['primary']) > 1) { unset($config['table']['sequenceName']); } foreach ($config['table']['columns'] as $columnName => $prop) { if (!isset($describeModel[strtoupper($columnName)])) { unset($config['table']['columns'][$columnName]); } } if (!isset($config['table']['unique'])) { $config['table']['unique'] = array(); } if (!isset($config['table']['description'])) { $config['table']['description'] = $config['table']['name']; /* $nameResponse = $this->_registry ->getClient() ->promptInteractiveInput("[ZendT] Informe a descricao da tabela?"); $description = $nameResponse->getContent(); $config['table']['description'] = utf8_encode($description); */ } $content = "<?php\nreturn " . var_export($config, true) . "\n?>"; file_put_contents($fileName, $content); $this->_print('Gerado o arquivo ' . $fileName); }
/** * Returns the column descriptions for a table. * * The return value is an associative array keyed by the column name, * as returned by the RDBMS. * * The value of each array element is an associative array * with the following keys: * * SCHEMA_NAME => string; name of database or schema * TABLE_NAME => string; * COLUMN_NAME => string; column name * COLUMN_POSITION => number; ordinal position of column in table * DATA_TYPE => string; SQL datatype name of column * DEFAULT => string; default expression of column, null if none * NULLABLE => boolean; true if column can have nulls * LENGTH => number; length of CHAR/VARCHAR * SCALE => number; scale of NUMERIC/DECIMAL * PRECISION => number; precision of NUMERIC/DECIMAL * UNSIGNED => boolean; unsigned property of an integer type * PRIMARY => boolean; true if column is part of the primary key * PRIMARY_POSITION => integer; position of column in primary key * * @param string $tableName table name * @param string $schemaName (optional) schema name * @return array */ public function describeTable($tableName, $schemaName = null) { return $this->_adapter->describeTable($tableName, $schemaName); }
/** * Initializes metadata. * * If metadata cannot be loaded from cache, adapter's describeTable() method is called to discover metadata * information. Returns true if and only if the metadata are loaded from cache. * * @return boolean * @throws Zend_Db_Table_Exception */ protected function _setupMetadata() { if ($this->metadataCacheInClass() && count($this->_metadata) > 0) { return true; } // Assume that metadata will be loaded from cache $isMetadataFromCache = true; // If $this has no metadata cache but the class has a default metadata cache if (null === $this->_metadataCache && null !== self::$_defaultMetadataCache) { // Make $this use the default metadata cache of the class $this->_setMetadataCache(self::$_defaultMetadataCache); } // If $this has a metadata cache if (null !== $this->_metadataCache) { // Define the cache identifier where the metadata are saved $cacheId = md5("{$this->_schema}.{$this->_name}"); } // If $this has no metadata cache or metadata cache misses if (null === $this->_metadataCache || !($metadata = $this->_metadataCache->load($cacheId))) { // Metadata are not loaded from cache $isMetadataFromCache = false; // Fetch metadata from the adapter's describeTable() method $metadata = $this->_db->describeTable($this->_name, $this->_schema); // If $this has a metadata cache, then cache the metadata if (null !== $this->_metadataCache && !$this->_metadataCache->save($metadata, $cacheId)) { /** * @see Zend_Db_Table_Exception */ // removed exception because we want that sql query to be executed even if metadata cache is not writable /* require_once 'Zend/Db/Table/Exception.php'; throw new Zend_Db_Table_Exception('Failed saving metadata to metadataCache'); */ } } // Assign the metadata to $this $this->_metadata = $metadata; // Return whether the metadata were loaded from cache return $isMetadataFromCache; }
/** * Initializes metadata. * * If metadata cannot be loaded from cache, adapter's describeTable() method is called to discover metadata * information. Returns true if and only if the metadata are loaded from cache. * * @return boolean * @throws Zend_Db_Table_Exception */ protected function _setupMetadata() { if ($this->metadataCacheInClass() && count($this->_metadata) > 0) { return true; } // Assume that metadata will be loaded from cache $isMetadataFromCache = true; // If $this has no metadata cache but the class has a default metadata cache if (null === $this->_metadataCache && null !== self::$_defaultMetadataCache) { // Make $this use the default metadata cache of the class $this->_setMetadataCache(self::$_defaultMetadataCache); } // If $this has a metadata cache if (null !== $this->_metadataCache) { // Define the cache identifier where the metadata are saved //get db configuration $dbConfig = $this->_db->getConfig(); $port = isset($dbConfig['options']['port']) ? ':' . $dbConfig['options']['port'] : (isset($dbConfig['port']) ? ':' . $dbConfig['port'] : null); $host = isset($dbConfig['options']['host']) ? ':' . $dbConfig['options']['host'] : (isset($dbConfig['host']) ? ':' . $dbConfig['host'] : null); // Define the cache identifier where the metadata are saved $cacheId = md5($port . $host . '/' . $dbConfig['dbname'] . ':' . $this->_schema . '.' . $this->_name); } // If $this has no metadata cache or metadata cache misses if (null === $this->_metadataCache || !($metadata = $this->_metadataCache->load($cacheId))) { // Metadata are not loaded from cache $isMetadataFromCache = false; // Fetch metadata from the adapter's describeTable() method $metadata = $this->_db->describeTable($this->_name, $this->_schema); // If $this has a metadata cache, then cache the metadata if (null !== $this->_metadataCache && !$this->_metadataCache->save($metadata, $cacheId)) { trigger_error('Failed saving metadata to metadataCache', E_USER_NOTICE); } } // Assign the metadata to $this $this->_metadata = $metadata; // Return whether the metadata were loaded from cache return $isMetadataFromCache; }
/** * checks if a given column {@param $_columnName} exists in table {@param $_tableName}. * * @param string $_columnName * @param string $_tableName * @return boolean */ public function columnExists($_columnName, $_tableName) { $tableName = SQL_TABLE_PREFIX . $_tableName; $tableInfo = $this->_db->describeTable($tableName); return array_key_exists($_columnName, $tableInfo); }